1//===- ScalarEvolution.cpp - Scalar Evolution Analysis --------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file contains the implementation of the scalar evolution analysis
10// engine, which is used primarily to analyze expressions involving induction
11// variables in loops.
12//
13// There are several aspects to this library. First is the representation of
14// scalar expressions, which are represented as subclasses of the SCEV class.
15// These classes are used to represent certain types of subexpressions that we
16// can handle. We only create one SCEV of a particular shape, so
17// pointer-comparisons for equality are legal.
18//
19// One important aspect of the SCEV objects is that they are never cyclic, even
20// if there is a cycle in the dataflow for an expression (ie, a PHI node). If
21// the PHI node is one of the idioms that we can represent (e.g., a polynomial
22// recurrence) then we represent it directly as a recurrence node, otherwise we
23// represent it as a SCEVUnknown node.
24//
25// In addition to being able to represent expressions of various types, we also
26// have folders that are used to build the *canonical* representation for a
27// particular expression. These folders are capable of using a variety of
28// rewrite rules to simplify the expressions.
29//
30// Once the folders are defined, we can implement the more interesting
31// higher-level code, such as the code that recognizes PHI nodes of various
32// types, computes the execution count of a loop, etc.
33//
34// TODO: We should use these routines and value representations to implement
35// dependence analysis!
36//
37//===----------------------------------------------------------------------===//
38//
39// There are several good references for the techniques used in this analysis.
40//
41// Chains of recurrences -- a method to expedite the evaluation
42// of closed-form functions
43// Olaf Bachmann, Paul S. Wang, Eugene V. Zima
44//
45// On computational properties of chains of recurrences
46// Eugene V. Zima
47//
48// Symbolic Evaluation of Chains of Recurrences for Loop Optimization
49// Robert A. van Engelen
50//
51// Efficient Symbolic Analysis for Optimizing Compilers
52// Robert A. van Engelen
53//
54// Using the chains of recurrences algebra for data dependence testing and
55// induction variable substitution
56// MS Thesis, Johnie Birch
57//
58//===----------------------------------------------------------------------===//
59
60#include "llvm/Analysis/ScalarEvolution.h"
61#include "llvm/ADT/APInt.h"
62#include "llvm/ADT/ArrayRef.h"
63#include "llvm/ADT/DenseMap.h"
64#include "llvm/ADT/DepthFirstIterator.h"
65#include "llvm/ADT/EquivalenceClasses.h"
66#include "llvm/ADT/FoldingSet.h"
67#include "llvm/ADT/None.h"
68#include "llvm/ADT/Optional.h"
69#include "llvm/ADT/STLExtras.h"
70#include "llvm/ADT/ScopeExit.h"
71#include "llvm/ADT/Sequence.h"
72#include "llvm/ADT/SetVector.h"
73#include "llvm/ADT/SmallPtrSet.h"
74#include "llvm/ADT/SmallSet.h"
75#include "llvm/ADT/SmallVector.h"
76#include "llvm/ADT/Statistic.h"
77#include "llvm/ADT/StringRef.h"
78#include "llvm/Analysis/AssumptionCache.h"
79#include "llvm/Analysis/ConstantFolding.h"
80#include "llvm/Analysis/InstructionSimplify.h"
81#include "llvm/Analysis/LoopInfo.h"
82#include "llvm/Analysis/ScalarEvolutionExpressions.h"
83#include "llvm/Analysis/TargetLibraryInfo.h"
84#include "llvm/Analysis/ValueTracking.h"
85#include "llvm/Config/llvm-config.h"
86#include "llvm/IR/Argument.h"
87#include "llvm/IR/BasicBlock.h"
88#include "llvm/IR/CFG.h"
89#include "llvm/IR/CallSite.h"
90#include "llvm/IR/Constant.h"
91#include "llvm/IR/ConstantRange.h"
92#include "llvm/IR/Constants.h"
93#include "llvm/IR/DataLayout.h"
94#include "llvm/IR/DerivedTypes.h"
95#include "llvm/IR/Dominators.h"
96#include "llvm/IR/Function.h"
97#include "llvm/IR/GlobalAlias.h"
98#include "llvm/IR/GlobalValue.h"
99#include "llvm/IR/GlobalVariable.h"
100#include "llvm/IR/InstIterator.h"
101#include "llvm/IR/InstrTypes.h"
102#include "llvm/IR/Instruction.h"
103#include "llvm/IR/Instructions.h"
104#include "llvm/IR/IntrinsicInst.h"
105#include "llvm/IR/Intrinsics.h"
106#include "llvm/IR/LLVMContext.h"
107#include "llvm/IR/Metadata.h"
108#include "llvm/IR/Operator.h"
109#include "llvm/IR/PatternMatch.h"
110#include "llvm/IR/Type.h"
111#include "llvm/IR/Use.h"
112#include "llvm/IR/User.h"
113#include "llvm/IR/Value.h"
114#include "llvm/IR/Verifier.h"
115#include "llvm/Pass.h"
116#include "llvm/Support/Casting.h"
117#include "llvm/Support/CommandLine.h"
118#include "llvm/Support/Compiler.h"
119#include "llvm/Support/Debug.h"
120#include "llvm/Support/ErrorHandling.h"
121#include "llvm/Support/KnownBits.h"
122#include "llvm/Support/SaveAndRestore.h"
123#include "llvm/Support/raw_ostream.h"
124#include <algorithm>
125#include <cassert>
126#include <climits>
127#include <cstddef>
128#include <cstdint>
129#include <cstdlib>
130#include <map>
131#include <memory>
132#include <tuple>
133#include <utility>
134#include <vector>
135
136using namespace llvm;
137
138#define DEBUG_TYPE "scalar-evolution"
139
140STATISTIC(NumArrayLenItCounts,
141 "Number of trip counts computed with array length");
142STATISTIC(NumTripCountsComputed,
143 "Number of loops with predictable loop counts");
144STATISTIC(NumTripCountsNotComputed,
145 "Number of loops without predictable loop counts");
146STATISTIC(NumBruteForceTripCountsComputed,
147 "Number of loops with trip counts computed by force");
148
149static cl::opt<unsigned>
150MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
151 cl::desc("Maximum number of iterations SCEV will "
152 "symbolically execute a constant "
153 "derived loop"),
154 cl::init(100));
155
156// FIXME: Enable this with EXPENSIVE_CHECKS when the test suite is clean.
157static cl::opt<bool> VerifySCEV(
158 "verify-scev", cl::Hidden,
159 cl::desc("Verify ScalarEvolution's backedge taken counts (slow)"));
160static cl::opt<bool>
161 VerifySCEVMap("verify-scev-maps", cl::Hidden,
162 cl::desc("Verify no dangling value in ScalarEvolution's "
163 "ExprValueMap (slow)"));
164
165static cl::opt<bool> VerifyIR(
166 "scev-verify-ir", cl::Hidden,
167 cl::desc("Verify IR correctness when making sensitive SCEV queries (slow)"),
168 cl::init(false));
169
170static cl::opt<unsigned> MulOpsInlineThreshold(
171 "scev-mulops-inline-threshold", cl::Hidden,
172 cl::desc("Threshold for inlining multiplication operands into a SCEV"),
173 cl::init(32));
174
175static cl::opt<unsigned> AddOpsInlineThreshold(
176 "scev-addops-inline-threshold", cl::Hidden,
177 cl::desc("Threshold for inlining addition operands into a SCEV"),
178 cl::init(500));
179
180static cl::opt<unsigned> MaxSCEVCompareDepth(
181 "scalar-evolution-max-scev-compare-depth", cl::Hidden,
182 cl::desc("Maximum depth of recursive SCEV complexity comparisons"),
183 cl::init(32));
184
185static cl::opt<unsigned> MaxSCEVOperationsImplicationDepth(
186 "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden,
187 cl::desc("Maximum depth of recursive SCEV operations implication analysis"),
188 cl::init(2));
189
190static cl::opt<unsigned> MaxValueCompareDepth(
191 "scalar-evolution-max-value-compare-depth", cl::Hidden,
192 cl::desc("Maximum depth of recursive value complexity comparisons"),
193 cl::init(2));
194
195static cl::opt<unsigned>
196 MaxArithDepth("scalar-evolution-max-arith-depth", cl::Hidden,
197 cl::desc("Maximum depth of recursive arithmetics"),
198 cl::init(32));
199
200static cl::opt<unsigned> MaxConstantEvolvingDepth(
201 "scalar-evolution-max-constant-evolving-depth", cl::Hidden,
202 cl::desc("Maximum depth of recursive constant evolving"), cl::init(32));
203
204static cl::opt<unsigned>
205 MaxCastDepth("scalar-evolution-max-cast-depth", cl::Hidden,
206 cl::desc("Maximum depth of recursive SExt/ZExt/Trunc"),
207 cl::init(8));
208
209static cl::opt<unsigned>
210 MaxAddRecSize("scalar-evolution-max-add-rec-size", cl::Hidden,
211 cl::desc("Max coefficients in AddRec during evolving"),
212 cl::init(8));
213
214static cl::opt<unsigned>
215 HugeExprThreshold("scalar-evolution-huge-expr-threshold", cl::Hidden,
216 cl::desc("Size of the expression which is considered huge"),
217 cl::init(4096));
218
219//===----------------------------------------------------------------------===//
220// SCEV class definitions
221//===----------------------------------------------------------------------===//
222
223//===----------------------------------------------------------------------===//
224// Implementation of the SCEV class.
225//
226
227#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
228LLVM_DUMP_METHOD void SCEV::dump() const {
229 print(dbgs());
230 dbgs() << '\n';
231}
232#endif
233
234void SCEV::print(raw_ostream &OS) const {
235 switch (static_cast<SCEVTypes>(getSCEVType())) {
236 case scConstant:
237 cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false);
238 return;
239 case scTruncate: {
240 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this);
241 const SCEV *Op = Trunc->getOperand();
242 OS << "(trunc " << *Op->getType() << " " << *Op << " to "
243 << *Trunc->getType() << ")";
244 return;
245 }
246 case scZeroExtend: {
247 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this);
248 const SCEV *Op = ZExt->getOperand();
249 OS << "(zext " << *Op->getType() << " " << *Op << " to "
250 << *ZExt->getType() << ")";
251 return;
252 }
253 case scSignExtend: {
254 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this);
255 const SCEV *Op = SExt->getOperand();
256 OS << "(sext " << *Op->getType() << " " << *Op << " to "
257 << *SExt->getType() << ")";
258 return;
259 }
260 case scAddRecExpr: {
261 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this);
262 OS << "{" << *AR->getOperand(0);
263 for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i)
264 OS << ",+," << *AR->getOperand(i);
265 OS << "}<";
266 if (AR->hasNoUnsignedWrap())
267 OS << "nuw><";
268 if (AR->hasNoSignedWrap())
269 OS << "nsw><";
270 if (AR->hasNoSelfWrap() &&
271 !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW)))
272 OS << "nw><";
273 AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false);
274 OS << ">";
275 return;
276 }
277 case scAddExpr:
278 case scMulExpr:
279 case scUMaxExpr:
280 case scSMaxExpr:
281 case scUMinExpr:
282 case scSMinExpr: {
283 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this);
284 const char *OpStr = nullptr;
285 switch (NAry->getSCEVType()) {
286 case scAddExpr: OpStr = " + "; break;
287 case scMulExpr: OpStr = " * "; break;
288 case scUMaxExpr: OpStr = " umax "; break;
289 case scSMaxExpr: OpStr = " smax "; break;
290 case scUMinExpr:
291 OpStr = " umin ";
292 break;
293 case scSMinExpr:
294 OpStr = " smin ";
295 break;
296 }
297 OS << "(";
298 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
299 I != E; ++I) {
300 OS << **I;
301 if (std::next(I) != E)
302 OS << OpStr;
303 }
304 OS << ")";
305 switch (NAry->getSCEVType()) {
306 case scAddExpr:
307 case scMulExpr:
308 if (NAry->hasNoUnsignedWrap())
309 OS << "<nuw>";
310 if (NAry->hasNoSignedWrap())
311 OS << "<nsw>";
312 }
313 return;
314 }
315 case scUDivExpr: {
316 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this);
317 OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")";
318 return;
319 }
320 case scUnknown: {
321 const SCEVUnknown *U = cast<SCEVUnknown>(this);
322 Type *AllocTy;
323 if (U->isSizeOf(AllocTy)) {
324 OS << "sizeof(" << *AllocTy << ")";
325 return;
326 }
327 if (U->isAlignOf(AllocTy)) {
328 OS << "alignof(" << *AllocTy << ")";
329 return;
330 }
331
332 Type *CTy;
333 Constant *FieldNo;
334 if (U->isOffsetOf(CTy, FieldNo)) {
335 OS << "offsetof(" << *CTy << ", ";
336 FieldNo->printAsOperand(OS, false);
337 OS << ")";
338 return;
339 }
340
341 // Otherwise just print it normally.
342 U->getValue()->printAsOperand(OS, false);
343 return;
344 }
345 case scCouldNotCompute:
346 OS << "***COULDNOTCOMPUTE***";
347 return;
348 }
349 llvm_unreachable("Unknown SCEV kind!");
350}
351
352Type *SCEV::getType() const {
353 switch (static_cast<SCEVTypes>(getSCEVType())) {
354 case scConstant:
355 return cast<SCEVConstant>(this)->getType();
356 case scTruncate:
357 case scZeroExtend:
358 case scSignExtend:
359 return cast<SCEVCastExpr>(this)->getType();
360 case scAddRecExpr:
361 case scMulExpr:
362 case scUMaxExpr:
363 case scSMaxExpr:
364 case scUMinExpr:
365 case scSMinExpr:
366 return cast<SCEVNAryExpr>(this)->getType();
367 case scAddExpr:
368 return cast<SCEVAddExpr>(this)->getType();
369 case scUDivExpr:
370 return cast<SCEVUDivExpr>(this)->getType();
371 case scUnknown:
372 return cast<SCEVUnknown>(this)->getType();
373 case scCouldNotCompute:
374 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
375 }
376 llvm_unreachable("Unknown SCEV kind!");
377}
378
379bool SCEV::isZero() const {
380 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
381 return SC->getValue()->isZero();
382 return false;
383}
384
385bool SCEV::isOne() const {
386 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
387 return SC->getValue()->isOne();
388 return false;
389}
390
391bool SCEV::isAllOnesValue() const {
392 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
393 return SC->getValue()->isMinusOne();
394 return false;
395}
396
397bool SCEV::isNonConstantNegative() const {
398 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this);
399 if (!Mul) return false;
400
401 // If there is a constant factor, it will be first.
402 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
403 if (!SC) return false;
404
405 // Return true if the value is negative, this matches things like (-42 * V).
406 return SC->getAPInt().isNegative();
407}
408
409SCEVCouldNotCompute::SCEVCouldNotCompute() :
410 SCEV(FoldingSetNodeIDRef(), scCouldNotCompute, 0) {}
411
412bool SCEVCouldNotCompute::classof(const SCEV *S) {
413 return S->getSCEVType() == scCouldNotCompute;
414}
415
416const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
417 FoldingSetNodeID ID;
418 ID.AddInteger(scConstant);
419 ID.AddPointer(V);
420 void *IP = nullptr;
421 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
422 SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
423 UniqueSCEVs.InsertNode(S, IP);
424 return S;
425}
426
427const SCEV *ScalarEvolution::getConstant(const APInt &Val) {
428 return getConstant(ConstantInt::get(getContext(), Val));
429}
430
431const SCEV *
432ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) {
433 IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
434 return getConstant(ConstantInt::get(ITy, V, isSigned));
435}
436
437SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID,
438 unsigned SCEVTy, const SCEV *op, Type *ty)
439 : SCEV(ID, SCEVTy, computeExpressionSize(op)), Op(op), Ty(ty) {}
440
441SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID,
442 const SCEV *op, Type *ty)
443 : SCEVCastExpr(ID, scTruncate, op, ty) {
444 assert(Op->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
445 "Cannot truncate non-integer value!");
446}
447
448SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,
449 const SCEV *op, Type *ty)
450 : SCEVCastExpr(ID, scZeroExtend, op, ty) {
451 assert(Op->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
452 "Cannot zero extend non-integer value!");
453}
454
455SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID,
456 const SCEV *op, Type *ty)
457 : SCEVCastExpr(ID, scSignExtend, op, ty) {
458 assert(Op->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
459 "Cannot sign extend non-integer value!");
460}
461
462void SCEVUnknown::deleted() {
463 // Clear this SCEVUnknown from various maps.
464 SE->forgetMemoizedResults(this);
465
466 // Remove this SCEVUnknown from the uniquing map.
467 SE->UniqueSCEVs.RemoveNode(this);
468
469 // Release the value.
470 setValPtr(nullptr);
471}
472
473void SCEVUnknown::allUsesReplacedWith(Value *New) {
474 // Remove this SCEVUnknown from the uniquing map.
475 SE->UniqueSCEVs.RemoveNode(this);
476
477 // Update this SCEVUnknown to point to the new value. This is needed
478 // because there may still be outstanding SCEVs which still point to
479 // this SCEVUnknown.
480 setValPtr(New);
481}
482
483bool SCEVUnknown::isSizeOf(Type *&AllocTy) const {
484 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
485 if (VCE->getOpcode() == Instruction::PtrToInt)
486 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
487 if (CE->getOpcode() == Instruction::GetElementPtr &&
488 CE->getOperand(0)->isNullValue() &&
489 CE->getNumOperands() == 2)
490 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
491 if (CI->isOne()) {
492 AllocTy = cast<PointerType>(CE->getOperand(0)->getType())
493 ->getElementType();
494 return true;
495 }
496
497 return false;
498}
499
500bool SCEVUnknown::isAlignOf(Type *&AllocTy) const {
501 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
502 if (VCE->getOpcode() == Instruction::PtrToInt)
503 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
504 if (CE->getOpcode() == Instruction::GetElementPtr &&
505 CE->getOperand(0)->isNullValue()) {
506 Type *Ty =
507 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
508 if (StructType *STy = dyn_cast<StructType>(Ty))
509 if (!STy->isPacked() &&
510 CE->getNumOperands() == 3 &&
511 CE->getOperand(1)->isNullValue()) {
512 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
513 if (CI->isOne() &&
514 STy->getNumElements() == 2 &&
515 STy->getElementType(0)->isIntegerTy(1)) {
516 AllocTy = STy->getElementType(1);
517 return true;
518 }
519 }
520 }
521
522 return false;
523}
524
525bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const {
526 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
527 if (VCE->getOpcode() == Instruction::PtrToInt)
528 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
529 if (CE->getOpcode() == Instruction::GetElementPtr &&
530 CE->getNumOperands() == 3 &&
531 CE->getOperand(0)->isNullValue() &&
532 CE->getOperand(1)->isNullValue()) {
533 Type *Ty =
534 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
535 // Ignore vector types here so that ScalarEvolutionExpander doesn't
536 // emit getelementptrs that index into vectors.
537 if (Ty->isStructTy() || Ty->isArrayTy()) {
538 CTy = Ty;
539 FieldNo = CE->getOperand(2);
540 return true;
541 }
542 }
543
544 return false;
545}
546
547//===----------------------------------------------------------------------===//
548// SCEV Utilities
549//===----------------------------------------------------------------------===//
550
551/// Compare the two values \p LV and \p RV in terms of their "complexity" where
552/// "complexity" is a partial (and somewhat ad-hoc) relation used to order
553/// operands in SCEV expressions. \p EqCache is a set of pairs of values that
554/// have been previously deemed to be "equally complex" by this routine. It is
555/// intended to avoid exponential time complexity in cases like:
556///
557/// %a = f(%x, %y)
558/// %b = f(%a, %a)
559/// %c = f(%b, %b)
560///
561/// %d = f(%x, %y)
562/// %e = f(%d, %d)
563/// %f = f(%e, %e)
564///
565/// CompareValueComplexity(%f, %c)
566///
567/// Since we do not continue running this routine on expression trees once we
568/// have seen unequal values, there is no need to track them in the cache.
569static int
570CompareValueComplexity(EquivalenceClasses<const Value *> &EqCacheValue,
571 const LoopInfo *const LI, Value *LV, Value *RV,
572 unsigned Depth) {
573 if (Depth > MaxValueCompareDepth || EqCacheValue.isEquivalent(LV, RV))
574 return 0;
575
576 // Order pointer values after integer values. This helps SCEVExpander form
577 // GEPs.
578 bool LIsPointer = LV->getType()->isPointerTy(),
579 RIsPointer = RV->getType()->isPointerTy();
580 if (LIsPointer != RIsPointer)
581 return (int)LIsPointer - (int)RIsPointer;
582
583 // Compare getValueID values.
584 unsigned LID = LV->getValueID(), RID = RV->getValueID();
585 if (LID != RID)
586 return (int)LID - (int)RID;
587
588 // Sort arguments by their position.
589 if (const auto *LA = dyn_cast<Argument>(LV)) {
590 const auto *RA = cast<Argument>(RV);
591 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
592 return (int)LArgNo - (int)RArgNo;
593 }
594
595 if (const auto *LGV = dyn_cast<GlobalValue>(LV)) {
596 const auto *RGV = cast<GlobalValue>(RV);
597
598 const auto IsGVNameSemantic = [&](const GlobalValue *GV) {
599 auto LT = GV->getLinkage();
600 return !(GlobalValue::isPrivateLinkage(LT) ||
601 GlobalValue::isInternalLinkage(LT));
602 };
603
604 // Use the names to distinguish the two values, but only if the
605 // names are semantically important.
606 if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV))
607 return LGV->getName().compare(RGV->getName());
608 }
609
610 // For instructions, compare their loop depth, and their operand count. This
611 // is pretty loose.
612 if (const auto *LInst = dyn_cast<Instruction>(LV)) {
613 const auto *RInst = cast<Instruction>(RV);
614
615 // Compare loop depths.
616 const BasicBlock *LParent = LInst->getParent(),
617 *RParent = RInst->getParent();
618 if (LParent != RParent) {
619 unsigned LDepth = LI->getLoopDepth(LParent),
620 RDepth = LI->getLoopDepth(RParent);
621 if (LDepth != RDepth)
622 return (int)LDepth - (int)RDepth;
623 }
624
625 // Compare the number of operands.
626 unsigned LNumOps = LInst->getNumOperands(),
627 RNumOps = RInst->getNumOperands();
628 if (LNumOps != RNumOps)
629 return (int)LNumOps - (int)RNumOps;
630
631 for (unsigned Idx : seq(0u, LNumOps)) {
632 int Result =
633 CompareValueComplexity(EqCacheValue, LI, LInst->getOperand(Idx),
634 RInst->getOperand(Idx), Depth + 1);
635 if (Result != 0)
636 return Result;
637 }
638 }
639
640 EqCacheValue.unionSets(LV, RV);
641 return 0;
642}
643
644// Return negative, zero, or positive, if LHS is less than, equal to, or greater
645// than RHS, respectively. A three-way result allows recursive comparisons to be
646// more efficient.
647static int CompareSCEVComplexity(
648 EquivalenceClasses<const SCEV *> &EqCacheSCEV,
649 EquivalenceClasses<const Value *> &EqCacheValue,
650 const LoopInfo *const LI, const SCEV *LHS, const SCEV *RHS,
651 DominatorTree &DT, unsigned Depth = 0) {
652 // Fast-path: SCEVs are uniqued so we can do a quick equality check.
653 if (LHS == RHS)
654 return 0;
655
656 // Primarily, sort the SCEVs by their getSCEVType().
657 unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
658 if (LType != RType)
659 return (int)LType - (int)RType;
660
661 if (Depth > MaxSCEVCompareDepth || EqCacheSCEV.isEquivalent(LHS, RHS))
662 return 0;
663 // Aside from the getSCEVType() ordering, the particular ordering
664 // isn't very important except that it's beneficial to be consistent,
665 // so that (a + b) and (b + a) don't end up as different expressions.
666 switch (static_cast<SCEVTypes>(LType)) {
667 case scUnknown: {
668 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
669 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
670
671 int X = CompareValueComplexity(EqCacheValue, LI, LU->getValue(),
672 RU->getValue(), Depth + 1);
673 if (X == 0)
674 EqCacheSCEV.unionSets(LHS, RHS);
675 return X;
676 }
677
678 case scConstant: {
679 const SCEVConstant *LC = cast<SCEVConstant>(LHS);
680 const SCEVConstant *RC = cast<SCEVConstant>(RHS);
681
682 // Compare constant values.
683 const APInt &LA = LC->getAPInt();
684 const APInt &RA = RC->getAPInt();
685 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
686 if (LBitWidth != RBitWidth)
687 return (int)LBitWidth - (int)RBitWidth;
688 return LA.ult(RA) ? -1 : 1;
689 }
690
691 case scAddRecExpr: {
692 const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS);
693 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
694
695 // There is always a dominance between two recs that are used by one SCEV,
696 // so we can safely sort recs by loop header dominance. We require such
697 // order in getAddExpr.
698 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
699 if (LLoop != RLoop) {
700 const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader();
701 assert(LHead != RHead && "Two loops share the same header?");
702 if (DT.dominates(LHead, RHead))
703 return 1;
704 else
705 assert(DT.dominates(RHead, LHead) &&
706 "No dominance between recurrences used by one SCEV?");
707 return -1;
708 }
709
710 // Addrec complexity grows with operand count.
711 unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands();
712 if (LNumOps != RNumOps)
713 return (int)LNumOps - (int)RNumOps;
714
715 // Lexicographically compare.
716 for (unsigned i = 0; i != LNumOps; ++i) {
717 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
718 LA->getOperand(i), RA->getOperand(i), DT,
719 Depth + 1);
720 if (X != 0)
721 return X;
722 }
723 EqCacheSCEV.unionSets(LHS, RHS);
724 return 0;
725 }
726
727 case scAddExpr:
728 case scMulExpr:
729 case scSMaxExpr:
730 case scUMaxExpr:
731 case scSMinExpr:
732 case scUMinExpr: {
733 const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS);
734 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
735
736 // Lexicographically compare n-ary expressions.
737 unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands();
738 if (LNumOps != RNumOps)
739 return (int)LNumOps - (int)RNumOps;
740
741 for (unsigned i = 0; i != LNumOps; ++i) {
742 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
743 LC->getOperand(i), RC->getOperand(i), DT,
744 Depth + 1);
745 if (X != 0)
746 return X;
747 }
748 EqCacheSCEV.unionSets(LHS, RHS);
749 return 0;
750 }
751
752 case scUDivExpr: {
753 const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS);
754 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
755
756 // Lexicographically compare udiv expressions.
757 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getLHS(),
758 RC->getLHS(), DT, Depth + 1);
759 if (X != 0)
760 return X;
761 X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getRHS(),
762 RC->getRHS(), DT, Depth + 1);
763 if (X == 0)
764 EqCacheSCEV.unionSets(LHS, RHS);
765 return X;
766 }
767
768 case scTruncate:
769 case scZeroExtend:
770 case scSignExtend: {
771 const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS);
772 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
773
774 // Compare cast expressions by operand.
775 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
776 LC->getOperand(), RC->getOperand(), DT,
777 Depth + 1);
778 if (X == 0)
779 EqCacheSCEV.unionSets(LHS, RHS);
780 return X;
781 }
782
783 case scCouldNotCompute:
784 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
785 }
786 llvm_unreachable("Unknown SCEV kind!");
787}
788
789/// Given a list of SCEV objects, order them by their complexity, and group
790/// objects of the same complexity together by value. When this routine is
791/// finished, we know that any duplicates in the vector are consecutive and that
792/// complexity is monotonically increasing.
793///
794/// Note that we go take special precautions to ensure that we get deterministic
795/// results from this routine. In other words, we don't want the results of
796/// this to depend on where the addresses of various SCEV objects happened to
797/// land in memory.
798static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
799 LoopInfo *LI, DominatorTree &DT) {
800 if (Ops.size() < 2) return; // Noop
801
802 EquivalenceClasses<const SCEV *> EqCacheSCEV;
803 EquivalenceClasses<const Value *> EqCacheValue;
804 if (Ops.size() == 2) {
805 // This is the common case, which also happens to be trivially simple.
806 // Special case it.
807 const SCEV *&LHS = Ops[0], *&RHS = Ops[1];
808 if (CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, RHS, LHS, DT) < 0)
809 std::swap(LHS, RHS);
810 return;
811 }
812
813 // Do the rough sort by complexity.
814 llvm::stable_sort(Ops, [&](const SCEV *LHS, const SCEV *RHS) {
815 return CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LHS, RHS, DT) <
816 0;
817 });
818
819 // Now that we are sorted by complexity, group elements of the same
820 // complexity. Note that this is, at worst, N^2, but the vector is likely to
821 // be extremely short in practice. Note that we take this approach because we
822 // do not want to depend on the addresses of the objects we are grouping.
823 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
824 const SCEV *S = Ops[i];
825 unsigned Complexity = S->getSCEVType();
826
827 // If there are any objects of the same complexity and same value as this
828 // one, group them.
829 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
830 if (Ops[j] == S) { // Found a duplicate.
831 // Move it to immediately after i'th element.
832 std::swap(Ops[i+1], Ops[j]);
833 ++i; // no need to rescan it.
834 if (i == e-2) return; // Done!
835 }
836 }
837 }
838}
839
840// Returns the size of the SCEV S.
841static inline int sizeOfSCEV(const SCEV *S) {
842 struct FindSCEVSize {
843 int Size = 0;
844
845 FindSCEVSize() = default;
846
847 bool follow(const SCEV *S) {
848 ++Size;
849 // Keep looking at all operands of S.
850 return true;
851 }
852
853 bool isDone() const {
854 return false;
855 }
856 };
857
858 FindSCEVSize F;
859 SCEVTraversal<FindSCEVSize> ST(F);
860 ST.visitAll(S);
861 return F.Size;
862}
863
864/// Returns true if the subtree of \p S contains at least HugeExprThreshold
865/// nodes.
866static bool isHugeExpression(const SCEV *S) {
867 return S->getExpressionSize() >= HugeExprThreshold;
868}
869
870/// Returns true of \p Ops contains a huge SCEV (see definition above).
871static bool hasHugeExpression(ArrayRef<const SCEV *> Ops) {
872 return any_of(Ops, isHugeExpression);
873}
874
875namespace {
876
877struct SCEVDivision : public SCEVVisitor<SCEVDivision, void> {
878public:
879 // Computes the Quotient and Remainder of the division of Numerator by
880 // Denominator.
881 static void divide(ScalarEvolution &SE, const SCEV *Numerator,
882 const SCEV *Denominator, const SCEV **Quotient,
883 const SCEV **Remainder) {
884 assert(Numerator && Denominator && "Uninitialized SCEV");
885
886 SCEVDivision D(SE, Numerator, Denominator);
887
888 // Check for the trivial case here to avoid having to check for it in the
889 // rest of the code.
890 if (Numerator == Denominator) {
891 *Quotient = D.One;
892 *Remainder = D.Zero;
893 return;
894 }
895
896 if (Numerator->isZero()) {
897 *Quotient = D.Zero;
898 *Remainder = D.Zero;
899 return;
900 }
901
902 // A simple case when N/1. The quotient is N.
903 if (Denominator->isOne()) {
904 *Quotient = Numerator;
905 *Remainder = D.Zero;
906 return;
907 }
908
909 // Split the Denominator when it is a product.
910 if (const SCEVMulExpr *T = dyn_cast<SCEVMulExpr>(Denominator)) {
911 const SCEV *Q, *R;
912 *Quotient = Numerator;
913 for (const SCEV *Op : T->operands()) {
914 divide(SE, *Quotient, Op, &Q, &R);
915 *Quotient = Q;
916
917 // Bail out when the Numerator is not divisible by one of the terms of
918 // the Denominator.
919 if (!R->isZero()) {
920 *Quotient = D.Zero;
921 *Remainder = Numerator;
922 return;
923 }
924 }
925 *Remainder = D.Zero;
926 return;
927 }
928
929 D.visit(Numerator);
930 *Quotient = D.Quotient;
931 *Remainder = D.Remainder;
932 }
933
934 // Except in the trivial case described above, we do not know how to divide
935 // Expr by Denominator for the following functions with empty implementation.
936 void visitTruncateExpr(const SCEVTruncateExpr *Numerator) {}
937 void visitZeroExtendExpr(const SCEVZeroExtendExpr *Numerator) {}
938 void visitSignExtendExpr(const SCEVSignExtendExpr *Numerator) {}
939 void visitUDivExpr(const SCEVUDivExpr *Numerator) {}
940 void visitSMaxExpr(const SCEVSMaxExpr *Numerator) {}
941 void visitUMaxExpr(const SCEVUMaxExpr *Numerator) {}
942 void visitSMinExpr(const SCEVSMinExpr *Numerator) {}
943 void visitUMinExpr(const SCEVUMinExpr *Numerator) {}
944 void visitUnknown(const SCEVUnknown *Numerator) {}
945 void visitCouldNotCompute(const SCEVCouldNotCompute *Numerator) {}
946
947 void visitConstant(const SCEVConstant *Numerator) {
948 if (const SCEVConstant *D = dyn_cast<SCEVConstant>(Denominator)) {
949 APInt NumeratorVal = Numerator->getAPInt();
950 APInt DenominatorVal = D->getAPInt();
951 uint32_t NumeratorBW = NumeratorVal.getBitWidth();
952 uint32_t DenominatorBW = DenominatorVal.getBitWidth();
953
954 if (NumeratorBW > DenominatorBW)
955 DenominatorVal = DenominatorVal.sext(NumeratorBW);
956 else if (NumeratorBW < DenominatorBW)
957 NumeratorVal = NumeratorVal.sext(DenominatorBW);
958
959 APInt QuotientVal(NumeratorVal.getBitWidth(), 0);
960 APInt RemainderVal(NumeratorVal.getBitWidth(), 0);
961 APInt::sdivrem(NumeratorVal, DenominatorVal, QuotientVal, RemainderVal);
962 Quotient = SE.getConstant(QuotientVal);
963 Remainder = SE.getConstant(RemainderVal);
964 return;
965 }
966 }
967
968 void visitAddRecExpr(const SCEVAddRecExpr *Numerator) {
969 const SCEV *StartQ, *StartR, *StepQ, *StepR;
970 if (!Numerator->isAffine())
971 return cannotDivide(Numerator);
972 divide(SE, Numerator->getStart(), Denominator, &StartQ, &StartR);
973 divide(SE, Numerator->getStepRecurrence(SE), Denominator, &StepQ, &StepR);
974 // Bail out if the types do not match.
975 Type *Ty = Denominator->getType();
976 if (Ty != StartQ->getType() || Ty != StartR->getType() ||
977 Ty != StepQ->getType() || Ty != StepR->getType())
978 return cannotDivide(Numerator);
979 Quotient = SE.getAddRecExpr(StartQ, StepQ, Numerator->getLoop(),
980 Numerator->getNoWrapFlags());
981 Remainder = SE.getAddRecExpr(StartR, StepR, Numerator->getLoop(),
982 Numerator->getNoWrapFlags());
983 }
984
985 void visitAddExpr(const SCEVAddExpr *Numerator) {
986 SmallVector<const SCEV *, 2> Qs, Rs;
987 Type *Ty = Denominator->getType();
988
989 for (const SCEV *Op : Numerator->operands()) {
990 const SCEV *Q, *R;
991 divide(SE, Op, Denominator, &Q, &R);
992
993 // Bail out if types do not match.
994 if (Ty != Q->getType() || Ty != R->getType())
995 return cannotDivide(Numerator);
996
997 Qs.push_back(Q);
998 Rs.push_back(R);
999 }
1000
1001 if (Qs.size() == 1) {
1002 Quotient = Qs[0];
1003 Remainder = Rs[0];
1004 return;
1005 }
1006
1007 Quotient = SE.getAddExpr(Qs);
1008 Remainder = SE.getAddExpr(Rs);
1009 }
1010
1011 void visitMulExpr(const SCEVMulExpr *Numerator) {
1012 SmallVector<const SCEV *, 2> Qs;
1013 Type *Ty = Denominator->getType();
1014
1015 bool FoundDenominatorTerm = false;
1016 for (const SCEV *Op : Numerator->operands()) {
1017 // Bail out if types do not match.
1018 if (Ty != Op->getType())
1019 return cannotDivide(Numerator);
1020
1021 if (FoundDenominatorTerm) {
1022 Qs.push_back(Op);
1023 continue;
1024 }
1025
1026 // Check whether Denominator divides one of the product operands.
1027 const SCEV *Q, *R;
1028 divide(SE, Op, Denominator, &Q, &R);
1029 if (!R->isZero()) {
1030 Qs.push_back(Op);
1031 continue;
1032 }
1033
1034 // Bail out if types do not match.
1035 if (Ty != Q->getType())
1036 return cannotDivide(Numerator);
1037
1038 FoundDenominatorTerm = true;
1039 Qs.push_back(Q);
1040 }
1041
1042 if (FoundDenominatorTerm) {
1043 Remainder = Zero;
1044 if (Qs.size() == 1)
1045 Quotient = Qs[0];
1046 else
1047 Quotient = SE.getMulExpr(Qs);
1048 return;
1049 }
1050
1051 if (!isa<SCEVUnknown>(Denominator))
1052 return cannotDivide(Numerator);
1053
1054 // The Remainder is obtained by replacing Denominator by 0 in Numerator.
1055 ValueToValueMap RewriteMap;
1056 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
1057 cast<SCEVConstant>(Zero)->getValue();
1058 Remainder = SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
1059
1060 if (Remainder->isZero()) {
1061 // The Quotient is obtained by replacing Denominator by 1 in Numerator.
1062 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
1063 cast<SCEVConstant>(One)->getValue();
1064 Quotient =
1065 SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
1066 return;
1067 }
1068
1069 // Quotient is (Numerator - Remainder) divided by Denominator.
1070 const SCEV *Q, *R;
1071 const SCEV *Diff = SE.getMinusSCEV(Numerator, Remainder);
1072 // This SCEV does not seem to simplify: fail the division here.
1073 if (sizeOfSCEV(Diff) > sizeOfSCEV(Numerator))
1074 return cannotDivide(Numerator);
1075 divide(SE, Diff, Denominator, &Q, &R);
1076 if (R != Zero)
1077 return cannotDivide(Numerator);
1078 Quotient = Q;
1079 }
1080
1081private:
1082 SCEVDivision(ScalarEvolution &S, const SCEV *Numerator,
1083 const SCEV *Denominator)
1084 : SE(S), Denominator(Denominator) {
1085 Zero = SE.getZero(Denominator->getType());
1086 One = SE.getOne(Denominator->getType());
1087
1088 // We generally do not know how to divide Expr by Denominator. We
1089 // initialize the division to a "cannot divide" state to simplify the rest
1090 // of the code.
1091 cannotDivide(Numerator);
1092 }
1093
1094 // Convenience function for giving up on the division. We set the quotient to
1095 // be equal to zero and the remainder to be equal to the numerator.
1096 void cannotDivide(const SCEV *Numerator) {
1097 Quotient = Zero;
1098 Remainder = Numerator;
1099 }
1100
1101 ScalarEvolution &SE;
1102 const SCEV *Denominator, *Quotient, *Remainder, *Zero, *One;
1103};
1104
1105} // end anonymous namespace
1106
1107//===----------------------------------------------------------------------===//
1108// Simple SCEV method implementations
1109//===----------------------------------------------------------------------===//
1110
1111/// Compute BC(It, K). The result has width W. Assume, K > 0.
1112static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
1113 ScalarEvolution &SE,
1114 Type *ResultTy) {
1115 // Handle the simplest case efficiently.
1116 if (K == 1)
1117 return SE.getTruncateOrZeroExtend(It, ResultTy);
1118
1119 // We are using the following formula for BC(It, K):
1120 //
1121 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
1122 //
1123 // Suppose, W is the bitwidth of the return value. We must be prepared for
1124 // overflow. Hence, we must assure that the result of our computation is
1125 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
1126 // safe in modular arithmetic.
1127 //
1128 // However, this code doesn't use exactly that formula; the formula it uses
1129 // is something like the following, where T is the number of factors of 2 in
1130 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
1131 // exponentiation:
1132 //
1133 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
1134 //
1135 // This formula is trivially equivalent to the previous formula. However,
1136 // this formula can be implemented much more efficiently. The trick is that
1137 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
1138 // arithmetic. To do exact division in modular arithmetic, all we have
1139 // to do is multiply by the inverse. Therefore, this step can be done at
1140 // width W.
1141 //
1142 // The next issue is how to safely do the division by 2^T. The way this
1143 // is done is by doing the multiplication step at a width of at least W + T
1144 // bits. This way, the bottom W+T bits of the product are accurate. Then,
1145 // when we perform the division by 2^T (which is equivalent to a right shift
1146 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
1147 // truncated out after the division by 2^T.
1148 //
1149 // In comparison to just directly using the first formula, this technique
1150 // is much more efficient; using the first formula requires W * K bits,
1151 // but this formula less than W + K bits. Also, the first formula requires
1152 // a division step, whereas this formula only requires multiplies and shifts.
1153 //
1154 // It doesn't matter whether the subtraction step is done in the calculation
1155 // width or the input iteration count's width; if the subtraction overflows,
1156 // the result must be zero anyway. We prefer here to do it in the width of
1157 // the induction variable because it helps a lot for certain cases; CodeGen
1158 // isn't smart enough to ignore the overflow, which leads to much less
1159 // efficient code if the width of the subtraction is wider than the native
1160 // register width.
1161 //
1162 // (It's possible to not widen at all by pulling out factors of 2 before
1163 // the multiplication; for example, K=2 can be calculated as
1164 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
1165 // extra arithmetic, so it's not an obvious win, and it gets
1166 // much more complicated for K > 3.)
1167
1168 // Protection from insane SCEVs; this bound is conservative,
1169 // but it probably doesn't matter.
1170 if (K > 1000)
1171 return SE.getCouldNotCompute();
1172
1173 unsigned W = SE.getTypeSizeInBits(ResultTy);
1174
1175 // Calculate K! / 2^T and T; we divide out the factors of two before
1176 // multiplying for calculating K! / 2^T to avoid overflow.
1177 // Other overflow doesn't matter because we only care about the bottom
1178 // W bits of the result.
1179 APInt OddFactorial(W, 1);
1180 unsigned T = 1;
1181 for (unsigned i = 3; i <= K; ++i) {
1182 APInt Mult(W, i);
1183 unsigned TwoFactors = Mult.countTrailingZeros();
1184 T += TwoFactors;
1185 Mult.lshrInPlace(TwoFactors);
1186 OddFactorial *= Mult;
1187 }
1188
1189 // We need at least W + T bits for the multiplication step
1190 unsigned CalculationBits = W + T;
1191
1192 // Calculate 2^T, at width T+W.
1193 APInt DivFactor = APInt::getOneBitSet(CalculationBits, T);
1194
1195 // Calculate the multiplicative inverse of K! / 2^T;
1196 // this multiplication factor will perform the exact division by
1197 // K! / 2^T.
1198 APInt Mod = APInt::getSignedMinValue(W+1);
1199 APInt MultiplyFactor = OddFactorial.zext(W+1);
1200 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
1201 MultiplyFactor = MultiplyFactor.trunc(W);
1202
1203 // Calculate the product, at width T+W
1204 IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
1205 CalculationBits);
1206 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
1207 for (unsigned i = 1; i != K; ++i) {
1208 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
1209 Dividend = SE.getMulExpr(Dividend,
1210 SE.getTruncateOrZeroExtend(S, CalculationTy));
1211 }
1212
1213 // Divide by 2^T
1214 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
1215
1216 // Truncate the result, and divide by K! / 2^T.
1217
1218 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
1219 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
1220}
1221
1222/// Return the value of this chain of recurrences at the specified iteration
1223/// number. We can evaluate this recurrence by multiplying each element in the
1224/// chain by the binomial coefficient corresponding to it. In other words, we
1225/// can evaluate {A,+,B,+,C,+,D} as:
1226///
1227/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
1228///
1229/// where BC(It, k) stands for binomial coefficient.
1230const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
1231 ScalarEvolution &SE) const {
1232 const SCEV *Result = getStart();
1233 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1234 // The computation is correct in the face of overflow provided that the
1235 // multiplication is performed _after_ the evaluation of the binomial
1236 // coefficient.
1237 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
1238 if (isa<SCEVCouldNotCompute>(Coeff))
1239 return Coeff;
1240
1241 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
1242 }
1243 return Result;
1244}
1245
1246//===----------------------------------------------------------------------===//
1247// SCEV Expression folder implementations
1248//===----------------------------------------------------------------------===//
1249
1250const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op, Type *Ty,
1251 unsigned Depth) {
1252 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
1253 "This is not a truncating conversion!");
1254 assert(isSCEVable(Ty) &&
1255 "This is not a conversion to a SCEVable type!");
1256 Ty = getEffectiveSCEVType(Ty);
1257
1258 FoldingSetNodeID ID;
1259 ID.AddInteger(scTruncate);
1260 ID.AddPointer(Op);
1261 ID.AddPointer(Ty);
1262 void *IP = nullptr;
1263 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1264
1265 // Fold if the operand is constant.
1266 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1267 return getConstant(
1268 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
1269
1270 // trunc(trunc(x)) --> trunc(x)
1271 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
1272 return getTruncateExpr(ST->getOperand(), Ty, Depth + 1);
1273
1274 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
1275 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1276 return getTruncateOrSignExtend(SS->getOperand(), Ty, Depth + 1);
1277
1278 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
1279 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1280 return getTruncateOrZeroExtend(SZ->getOperand(), Ty, Depth + 1);
1281
1282 if (Depth > MaxCastDepth) {
1283 SCEV *S =
1284 new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), Op, Ty);
1285 UniqueSCEVs.InsertNode(S, IP);
1286 addToLoopUseLists(S);
1287 return S;
1288 }
1289
1290 // trunc(x1 + ... + xN) --> trunc(x1) + ... + trunc(xN) and
1291 // trunc(x1 * ... * xN) --> trunc(x1) * ... * trunc(xN),
1292 // if after transforming we have at most one truncate, not counting truncates
1293 // that replace other casts.
1294 if (isa<SCEVAddExpr>(Op) || isa<SCEVMulExpr>(Op)) {
1295 auto *CommOp = cast<SCEVCommutativeExpr>(Op);
1296 SmallVector<const SCEV *, 4> Operands;
1297 unsigned numTruncs = 0;
1298 for (unsigned i = 0, e = CommOp->getNumOperands(); i != e && numTruncs < 2;
1299 ++i) {
1300 const SCEV *S = getTruncateExpr(CommOp->getOperand(i), Ty, Depth + 1);
1301 if (!isa<SCEVCastExpr>(CommOp->getOperand(i)) && isa<SCEVTruncateExpr>(S))
1302 numTruncs++;
1303 Operands.push_back(S);
1304 }
1305 if (numTruncs < 2) {
1306 if (isa<SCEVAddExpr>(Op))
1307 return getAddExpr(Operands);
1308 else if (isa<SCEVMulExpr>(Op))
1309 return getMulExpr(Operands);
1310 else
1311 llvm_unreachable("Unexpected SCEV type for Op.");
1312 }
1313 // Although we checked in the beginning that ID is not in the cache, it is
1314 // possible that during recursion and different modification ID was inserted
1315 // into the cache. So if we find it, just return it.
1316 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
1317 return S;
1318 }
1319
1320 // If the input value is a chrec scev, truncate the chrec's operands.
1321 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
1322 SmallVector<const SCEV *, 4> Operands;
1323 for (const SCEV *Op : AddRec->operands())
1324 Operands.push_back(getTruncateExpr(Op, Ty, Depth + 1));
1325 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap);
1326 }
1327
1328 // The cast wasn't folded; create an explicit cast node. We can reuse
1329 // the existing insert position since if we get here, we won't have
1330 // made any changes which would invalidate it.
1331 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
1332 Op, Ty);
1333 UniqueSCEVs.InsertNode(S, IP);
1334 addToLoopUseLists(S);
1335 return S;
1336}
1337
1338// Get the limit of a recurrence such that incrementing by Step cannot cause
1339// signed overflow as long as the value of the recurrence within the
1340// loop does not exceed this limit before incrementing.
1341static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step,
1342 ICmpInst::Predicate *Pred,
1343 ScalarEvolution *SE) {
1344 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1345 if (SE->isKnownPositive(Step)) {
1346 *Pred = ICmpInst::ICMP_SLT;
1347 return SE->getConstant(APInt::getSignedMinValue(BitWidth) -
1348 SE->getSignedRangeMax(Step));
1349 }
1350 if (SE->isKnownNegative(Step)) {
1351 *Pred = ICmpInst::ICMP_SGT;
1352 return SE->getConstant(APInt::getSignedMaxValue(BitWidth) -
1353 SE->getSignedRangeMin(Step));
1354 }
1355 return nullptr;
1356}
1357
1358// Get the limit of a recurrence such that incrementing by Step cannot cause
1359// unsigned overflow as long as the value of the recurrence within the loop does
1360// not exceed this limit before incrementing.
1361static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step,
1362 ICmpInst::Predicate *Pred,
1363 ScalarEvolution *SE) {
1364 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1365 *Pred = ICmpInst::ICMP_ULT;
1366
1367 return SE->getConstant(APInt::getMinValue(BitWidth) -
1368 SE->getUnsignedRangeMax(Step));
1369}
1370
1371namespace {
1372
1373struct ExtendOpTraitsBase {
1374 typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *,
1375 unsigned);
1376};
1377
1378// Used to make code generic over signed and unsigned overflow.
1379template <typename ExtendOp> struct ExtendOpTraits {
1380 // Members present:
1381 //
1382 // static const SCEV::NoWrapFlags WrapType;
1383 //
1384 // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr;
1385 //
1386 // static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1387 // ICmpInst::Predicate *Pred,
1388 // ScalarEvolution *SE);
1389};
1390
1391template <>
1392struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase {
1393 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW;
1394
1395 static const GetExtendExprTy GetExtendExpr;
1396
1397 static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1398 ICmpInst::Predicate *Pred,
1399 ScalarEvolution *SE) {
1400 return getSignedOverflowLimitForStep(Step, Pred, SE);
1401 }
1402};
1403
1404const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1405 SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr;
1406
1407template <>
1408struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase {
1409 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW;
1410
1411 static const GetExtendExprTy GetExtendExpr;
1412
1413 static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1414 ICmpInst::Predicate *Pred,
1415 ScalarEvolution *SE) {
1416 return getUnsignedOverflowLimitForStep(Step, Pred, SE);
1417 }
1418};
1419
1420const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1421 SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr;
1422
1423} // end anonymous namespace
1424
1425// The recurrence AR has been shown to have no signed/unsigned wrap or something
1426// close to it. Typically, if we can prove NSW/NUW for AR, then we can just as
1427// easily prove NSW/NUW for its preincrement or postincrement sibling. This
1428// allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step +
1429// Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the
1430// expression "Step + sext/zext(PreIncAR)" is congruent with
1431// "sext/zext(PostIncAR)"
1432template <typename ExtendOpTy>
1433static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty,
1434 ScalarEvolution *SE, unsigned Depth) {
1435 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1436 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1437
1438 const Loop *L = AR->getLoop();
1439 const SCEV *Start = AR->getStart();
1440 const SCEV *Step = AR->getStepRecurrence(*SE);
1441
1442 // Check for a simple looking step prior to loop entry.
1443 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
1444 if (!SA)
1445 return nullptr;
1446
1447 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
1448 // subtraction is expensive. For this purpose, perform a quick and dirty
1449 // difference, by checking for Step in the operand list.
1450 SmallVector<const SCEV *, 4> DiffOps;
1451 for (const SCEV *Op : SA->operands())
1452 if (Op != Step)
1453 DiffOps.push_back(Op);
1454
1455 if (DiffOps.size() == SA->getNumOperands())
1456 return nullptr;
1457
1458 // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` +
1459 // `Step`:
1460
1461 // 1. NSW/NUW flags on the step increment.
1462 auto PreStartFlags =
1463 ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW);
1464 const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags);
1465 const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>(
1466 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap));
1467
1468 // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies
1469 // "S+X does not sign/unsign-overflow".
1470 //
1471
1472 const SCEV *BECount = SE->getBackedgeTakenCount(L);
1473 if (PreAR && PreAR->getNoWrapFlags(WrapType) &&
1474 !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount))
1475 return PreStart;
1476
1477 // 2. Direct overflow check on the step operation's expression.
1478 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
1479 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
1480 const SCEV *OperandExtendedStart =
1481 SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth),
1482 (SE->*GetExtendExpr)(Step, WideTy, Depth));
1483 if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) {
1484 if (PreAR && AR->getNoWrapFlags(WrapType)) {
1485 // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW
1486 // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then
1487 // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact.
1488 const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(WrapType);
1489 }
1490 return PreStart;
1491 }
1492
1493 // 3. Loop precondition.
1494 ICmpInst::Predicate Pred;
1495 const SCEV *OverflowLimit =
1496 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE);
1497
1498 if (OverflowLimit &&
1499 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit))
1500 return PreStart;
1501
1502 return nullptr;
1503}
1504
1505// Get the normalized zero or sign extended expression for this AddRec's Start.
1506template <typename ExtendOpTy>
1507static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty,
1508 ScalarEvolution *SE,
1509 unsigned Depth) {
1510 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1511
1512 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Depth);
1513 if (!PreStart)
1514 return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth);
1515
1516 return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty,
1517 Depth),
1518 (SE->*GetExtendExpr)(PreStart, Ty, Depth));
1519}
1520
1521// Try to prove away overflow by looking at "nearby" add recurrences. A
1522// motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it
1523// does not itself wrap then we can conclude that `{1,+,4}` is `nuw`.
1524//
1525// Formally:
1526//
1527// {S,+,X} == {S-T,+,X} + T
1528// => Ext({S,+,X}) == Ext({S-T,+,X} + T)
1529//
1530// If ({S-T,+,X} + T) does not overflow ... (1)
1531//
1532// RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T)
1533//
1534// If {S-T,+,X} does not overflow ... (2)
1535//
1536// RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T)
1537// == {Ext(S-T)+Ext(T),+,Ext(X)}
1538//
1539// If (S-T)+T does not overflow ... (3)
1540//
1541// RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)}
1542// == {Ext(S),+,Ext(X)} == LHS
1543//
1544// Thus, if (1), (2) and (3) are true for some T, then
1545// Ext({S,+,X}) == {Ext(S),+,Ext(X)}
1546//
1547// (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T)
1548// does not overflow" restricted to the 0th iteration. Therefore we only need
1549// to check for (1) and (2).
1550//
1551// In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T
1552// is `Delta` (defined below).
1553template <typename ExtendOpTy>
1554bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start,
1555 const SCEV *Step,
1556 const Loop *L) {
1557 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1558
1559 // We restrict `Start` to a constant to prevent SCEV from spending too much
1560 // time here. It is correct (but more expensive) to continue with a
1561 // non-constant `Start` and do a general SCEV subtraction to compute
1562 // `PreStart` below.
1563 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start);
1564 if (!StartC)
1565 return false;
1566
1567 APInt StartAI = StartC->getAPInt();
1568
1569 for (unsigned Delta : {-2, -1, 1, 2}) {
1570 const SCEV *PreStart = getConstant(StartAI - Delta);
1571
1572 FoldingSetNodeID ID;
1573 ID.AddInteger(scAddRecExpr);
1574 ID.AddPointer(PreStart);
1575 ID.AddPointer(Step);
1576 ID.AddPointer(L);
1577 void *IP = nullptr;
1578 const auto *PreAR =
1579 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1580
1581 // Give up if we don't already have the add recurrence we need because
1582 // actually constructing an add recurrence is relatively expensive.
1583 if (PreAR && PreAR->getNoWrapFlags(WrapType)) { // proves (2)
1584 const SCEV *DeltaS = getConstant(StartC->getType(), Delta);
1585 ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
1586 const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(
1587 DeltaS, &Pred, this);
1588 if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1)
1589 return true;
1590 }
1591 }
1592
1593 return false;
1594}
1595
1596// Finds an integer D for an expression (C + x + y + ...) such that the top
1597// level addition in (D + (C - D + x + y + ...)) would not wrap (signed or
1598// unsigned) and the number of trailing zeros of (C - D + x + y + ...) is
1599// maximized, where C is the \p ConstantTerm, x, y, ... are arbitrary SCEVs, and
1600// the (C + x + y + ...) expression is \p WholeAddExpr.
1601static APInt extractConstantWithoutWrapping(ScalarEvolution &SE,
1602 const SCEVConstant *ConstantTerm,
1603 const SCEVAddExpr *WholeAddExpr) {
1604 const APInt C = ConstantTerm->getAPInt();
1605 const unsigned BitWidth = C.getBitWidth();
1606 // Find number of trailing zeros of (x + y + ...) w/o the C first:
1607 uint32_t TZ = BitWidth;
1608 for (unsigned I = 1, E = WholeAddExpr->getNumOperands(); I < E && TZ; ++I)
1609 TZ = std::min(TZ, SE.GetMinTrailingZeros(WholeAddExpr->getOperand(I)));
1610 if (TZ) {
1611 // Set D to be as many least significant bits of C as possible while still
1612 // guaranteeing that adding D to (C - D + x + y + ...) won't cause a wrap:
1613 return TZ < BitWidth ? C.trunc(TZ).zext(BitWidth) : C;
1614 }
1615 return APInt(BitWidth, 0);
1616}
1617
1618// Finds an integer D for an affine AddRec expression {C,+,x} such that the top
1619// level addition in (D + {C-D,+,x}) would not wrap (signed or unsigned) and the
1620// number of trailing zeros of (C - D + x * n) is maximized, where C is the \p
1621// ConstantStart, x is an arbitrary \p Step, and n is the loop trip count.
1622static APInt extractConstantWithoutWrapping(ScalarEvolution &SE,
1623 const APInt &ConstantStart,
1624 const SCEV *Step) {
1625 const unsigned BitWidth = ConstantStart.getBitWidth();
1626 const uint32_t TZ = SE.GetMinTrailingZeros(Step);
1627 if (TZ)
1628 return TZ < BitWidth ? ConstantStart.trunc(TZ).zext(BitWidth)
1629 : ConstantStart;
1630 return APInt(BitWidth, 0);
1631}
1632
1633const SCEV *
1634ScalarEvolution::getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) {
1635 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1636 "This is not an extending conversion!");
1637 assert(isSCEVable(Ty) &&
1638 "This is not a conversion to a SCEVable type!");
1639 Ty = getEffectiveSCEVType(Ty);
1640
1641 // Fold if the operand is constant.
1642 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1643 return getConstant(
1644 cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty)));
1645
1646 // zext(zext(x)) --> zext(x)
1647 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1648 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1649
1650 // Before doing any expensive analysis, check to see if we've already
1651 // computed a SCEV for this Op and Ty.
1652 FoldingSetNodeID ID;
1653 ID.AddInteger(scZeroExtend);
1654 ID.AddPointer(Op);
1655 ID.AddPointer(Ty);
1656 void *IP = nullptr;
1657 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1658 if (Depth > MaxCastDepth) {
1659 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1660 Op, Ty);
1661 UniqueSCEVs.InsertNode(S, IP);
1662 addToLoopUseLists(S);
1663 return S;
1664 }
1665
1666 // zext(trunc(x)) --> zext(x) or x or trunc(x)
1667 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1668 // It's possible the bits taken off by the truncate were all zero bits. If
1669 // so, we should be able to simplify this further.
1670 const SCEV *X = ST->getOperand();
1671 ConstantRange CR = getUnsignedRange(X);
1672 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1673 unsigned NewBits = getTypeSizeInBits(Ty);
1674 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
1675 CR.zextOrTrunc(NewBits)))
1676 return getTruncateOrZeroExtend(X, Ty, Depth);
1677 }
1678
1679 // If the input value is a chrec scev, and we can prove that the value
1680 // did not overflow the old, smaller, value, we can zero extend all of the
1681 // operands (often constants). This allows analysis of something like
1682 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
1683 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1684 if (AR->isAffine()) {
1685 const SCEV *Start = AR->getStart();
1686 const SCEV *Step = AR->getStepRecurrence(*this);
1687 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1688 const Loop *L = AR->getLoop();
1689
1690 if (!AR->hasNoUnsignedWrap()) {
1691 auto NewFlags = proveNoWrapViaConstantRanges(AR);
1692 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags);
1693 }
1694
1695 // If we have special knowledge that this addrec won't overflow,
1696 // we don't need to do any further analysis.
1697 if (AR->hasNoUnsignedWrap())
1698 return getAddRecExpr(
1699 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1),
1700 getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
1701
1702 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1703 // Note that this serves two purposes: It filters out loops that are
1704 // simply not analyzable, and it covers the case where this code is
1705 // being called from within backedge-taken count analysis, such that
1706 // attempting to ask for the backedge-taken count would likely result
1707 // in infinite recursion. In the later case, the analysis code will
1708 // cope with a conservative value, and it will take care to purge
1709 // that value once it has finished.
1710 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
1711 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1712 // Manually compute the final value for AR, checking for
1713 // overflow.
1714
1715 // Check whether the backedge-taken count can be losslessly casted to
1716 // the addrec's type. The count is always unsigned.
1717 const SCEV *CastedMaxBECount =
1718 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth);
1719 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend(
1720 CastedMaxBECount, MaxBECount->getType(), Depth);
1721 if (MaxBECount == RecastedMaxBECount) {
1722 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1723 // Check whether Start+Step*MaxBECount has no unsigned overflow.
1724 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step,
1725 SCEV::FlagAnyWrap, Depth + 1);
1726 const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul,
1727 SCEV::FlagAnyWrap,
1728 Depth + 1),
1729 WideTy, Depth + 1);
1730 const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1);
1731 const SCEV *WideMaxBECount =
1732 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
1733 const SCEV *OperandExtendedAdd =
1734 getAddExpr(WideStart,
1735 getMulExpr(WideMaxBECount,
1736 getZeroExtendExpr(Step, WideTy, Depth + 1),
1737 SCEV::FlagAnyWrap, Depth + 1),
1738 SCEV::FlagAnyWrap, Depth + 1);
1739 if (ZAdd == OperandExtendedAdd) {
1740 // Cache knowledge of AR NUW, which is propagated to this AddRec.
1741 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1742 // Return the expression with the addrec on the outside.
1743 return getAddRecExpr(
1744 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1745 Depth + 1),
1746 getZeroExtendExpr(Step, Ty, Depth + 1), L,
1747 AR->getNoWrapFlags());
1748 }
1749 // Similar to above, only this time treat the step value as signed.
1750 // This covers loops that count down.
1751 OperandExtendedAdd =
1752 getAddExpr(WideStart,
1753 getMulExpr(WideMaxBECount,
1754 getSignExtendExpr(Step, WideTy, Depth + 1),
1755 SCEV::FlagAnyWrap, Depth + 1),
1756 SCEV::FlagAnyWrap, Depth + 1);
1757 if (ZAdd == OperandExtendedAdd) {
1758 // Cache knowledge of AR NW, which is propagated to this AddRec.
1759 // Negative step causes unsigned wrap, but it still can't self-wrap.
1760 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1761 // Return the expression with the addrec on the outside.
1762 return getAddRecExpr(
1763 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1764 Depth + 1),
1765 getSignExtendExpr(Step, Ty, Depth + 1), L,
1766 AR->getNoWrapFlags());
1767 }
1768 }
1769 }
1770
1771 // Normally, in the cases we can prove no-overflow via a
1772 // backedge guarding condition, we can also compute a backedge
1773 // taken count for the loop. The exceptions are assumptions and
1774 // guards present in the loop -- SCEV is not great at exploiting
1775 // these to compute max backedge taken counts, but can still use
1776 // these to prove lack of overflow. Use this fact to avoid
1777 // doing extra work that may not pay off.
1778 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1779 !AC.assumptions().empty()) {
1780 // If the backedge is guarded by a comparison with the pre-inc
1781 // value the addrec is safe. Also, if the entry is guarded by
1782 // a comparison with the start value and the backedge is
1783 // guarded by a comparison with the post-inc value, the addrec
1784 // is safe.
1785 if (isKnownPositive(Step)) {
1786 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
1787 getUnsignedRangeMax(Step));
1788 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
1789 isKnownOnEveryIteration(ICmpInst::ICMP_ULT, AR, N)) {
1790 // Cache knowledge of AR NUW, which is propagated to this
1791 // AddRec.
1792 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1793 // Return the expression with the addrec on the outside.
1794 return getAddRecExpr(
1795 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1796 Depth + 1),
1797 getZeroExtendExpr(Step, Ty, Depth + 1), L,
1798 AR->getNoWrapFlags());
1799 }
1800 } else if (isKnownNegative(Step)) {
1801 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
1802 getSignedRangeMin(Step));
1803 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
1804 isKnownOnEveryIteration(ICmpInst::ICMP_UGT, AR, N)) {
1805 // Cache knowledge of AR NW, which is propagated to this
1806 // AddRec. Negative step causes unsigned wrap, but it
1807 // still can't self-wrap.
1808 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1809 // Return the expression with the addrec on the outside.
1810 return getAddRecExpr(
1811 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1812 Depth + 1),
1813 getSignExtendExpr(Step, Ty, Depth + 1), L,
1814 AR->getNoWrapFlags());
1815 }
1816 }
1817 }
1818
1819 // zext({C,+,Step}) --> (zext(D) + zext({C-D,+,Step}))<nuw><nsw>
1820 // if D + (C - D + Step * n) could be proven to not unsigned wrap
1821 // where D maximizes the number of trailing zeros of (C - D + Step * n)
1822 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
1823 const APInt &C = SC->getAPInt();
1824 const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
1825 if (D != 0) {
1826 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1827 const SCEV *SResidual =
1828 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
1829 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1830 return getAddExpr(SZExtD, SZExtR,
1831 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
1832 Depth + 1);
1833 }
1834 }
1835
1836 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) {
1837 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1838 return getAddRecExpr(
1839 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1),
1840 getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
1841 }
1842 }
1843
1844 // zext(A % B) --> zext(A) % zext(B)
1845 {
1846 const SCEV *LHS;
1847 const SCEV *RHS;
1848 if (matchURem(Op, LHS, RHS))
1849 return getURemExpr(getZeroExtendExpr(LHS, Ty, Depth + 1),
1850 getZeroExtendExpr(RHS, Ty, Depth + 1));
1851 }
1852
1853 // zext(A / B) --> zext(A) / zext(B).
1854 if (auto *Div = dyn_cast<SCEVUDivExpr>(Op))
1855 return getUDivExpr(getZeroExtendExpr(Div->getLHS(), Ty, Depth + 1),
1856 getZeroExtendExpr(Div->getRHS(), Ty, Depth + 1));
1857
1858 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1859 // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw>
1860 if (SA->hasNoUnsignedWrap()) {
1861 // If the addition does not unsign overflow then we can, by definition,
1862 // commute the zero extension with the addition operation.
1863 SmallVector<const SCEV *, 4> Ops;
1864 for (const auto *Op : SA->operands())
1865 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1866 return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1);
1867 }
1868
1869 // zext(C + x + y + ...) --> (zext(D) + zext((C - D) + x + y + ...))
1870 // if D + (C - D + x + y + ...) could be proven to not unsigned wrap
1871 // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
1872 //
1873 // Often address arithmetics contain expressions like
1874 // (zext (add (shl X, C1), C2)), for instance, (zext (5 + (4 * X))).
1875 // This transformation is useful while proving that such expressions are
1876 // equal or differ by a small constant amount, see LoadStoreVectorizer pass.
1877 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
1878 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
1879 if (D != 0) {
1880 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1881 const SCEV *SResidual =
1882 getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth);
1883 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1884 return getAddExpr(SZExtD, SZExtR,
1885 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
1886 Depth + 1);
1887 }
1888 }
1889 }
1890
1891 if (auto *SM = dyn_cast<SCEVMulExpr>(Op)) {
1892 // zext((A * B * ...)<nuw>) --> (zext(A) * zext(B) * ...)<nuw>
1893 if (SM->hasNoUnsignedWrap()) {
1894 // If the multiply does not unsign overflow then we can, by definition,
1895 // commute the zero extension with the multiply operation.
1896 SmallVector<const SCEV *, 4> Ops;
1897 for (const auto *Op : SM->operands())
1898 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1899 return getMulExpr(Ops, SCEV::FlagNUW, Depth + 1);
1900 }
1901
1902 // zext(2^K * (trunc X to iN)) to iM ->
1903 // 2^K * (zext(trunc X to i{N-K}) to iM)<nuw>
1904 //
1905 // Proof:
1906 //
1907 // zext(2^K * (trunc X to iN)) to iM
1908 // = zext((trunc X to iN) << K) to iM
1909 // = zext((trunc X to i{N-K}) << K)<nuw> to iM
1910 // (because shl removes the top K bits)
1911 // = zext((2^K * (trunc X to i{N-K}))<nuw>) to iM
1912 // = (2^K * (zext(trunc X to i{N-K}) to iM))<nuw>.
1913 //
1914 if (SM->getNumOperands() == 2)
1915 if (auto *MulLHS = dyn_cast<SCEVConstant>(SM->getOperand(0)))
1916 if (MulLHS->getAPInt().isPowerOf2())
1917 if (auto *TruncRHS = dyn_cast<SCEVTruncateExpr>(SM->getOperand(1))) {
1918 int NewTruncBits = getTypeSizeInBits(TruncRHS->getType()) -
1919 MulLHS->getAPInt().logBase2();
1920 Type *NewTruncTy = IntegerType::get(getContext(), NewTruncBits);
1921 return getMulExpr(
1922 getZeroExtendExpr(MulLHS, Ty),
1923 getZeroExtendExpr(
1924 getTruncateExpr(TruncRHS->getOperand(), NewTruncTy), Ty),
1925 SCEV::FlagNUW, Depth + 1);
1926 }
1927 }
1928
1929 // The cast wasn't folded; create an explicit cast node.
1930 // Recompute the insert position, as it may have been invalidated.
1931 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1932 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1933 Op, Ty);
1934 UniqueSCEVs.InsertNode(S, IP);
1935 addToLoopUseLists(S);
1936 return S;
1937}
1938
1939const SCEV *
1940ScalarEvolution::getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) {
1941 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1942 "This is not an extending conversion!");
1943 assert(isSCEVable(Ty) &&
1944 "This is not a conversion to a SCEVable type!");
1945 Ty = getEffectiveSCEVType(Ty);
1946
1947 // Fold if the operand is constant.
1948 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1949 return getConstant(
1950 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty)));
1951
1952 // sext(sext(x)) --> sext(x)
1953 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1954 return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1);
1955
1956 // sext(zext(x)) --> zext(x)
1957 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1958 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1959
1960 // Before doing any expensive analysis, check to see if we've already
1961 // computed a SCEV for this Op and Ty.
1962 FoldingSetNodeID ID;
1963 ID.AddInteger(scSignExtend);
1964 ID.AddPointer(Op);
1965 ID.AddPointer(Ty);
1966 void *IP = nullptr;
1967 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1968 // Limit recursion depth.
1969 if (Depth > MaxCastDepth) {
1970 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1971 Op, Ty);
1972 UniqueSCEVs.InsertNode(S, IP);
1973 addToLoopUseLists(S);
1974 return S;
1975 }
1976
1977 // sext(trunc(x)) --> sext(x) or x or trunc(x)
1978 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1979 // It's possible the bits taken off by the truncate were all sign bits. If
1980 // so, we should be able to simplify this further.
1981 const SCEV *X = ST->getOperand();
1982 ConstantRange CR = getSignedRange(X);
1983 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1984 unsigned NewBits = getTypeSizeInBits(Ty);
1985 if (CR.truncate(TruncBits).signExtend(NewBits).contains(
1986 CR.sextOrTrunc(NewBits)))
1987 return getTruncateOrSignExtend(X, Ty, Depth);
1988 }
1989
1990 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1991 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
1992 if (SA->hasNoSignedWrap()) {
1993 // If the addition does not sign overflow then we can, by definition,
1994 // commute the sign extension with the addition operation.
1995 SmallVector<const SCEV *, 4> Ops;
1996 for (const auto *Op : SA->operands())
1997 Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1));
1998 return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1);
1999 }
2000
2001 // sext(C + x + y + ...) --> (sext(D) + sext((C - D) + x + y + ...))
2002 // if D + (C - D + x + y + ...) could be proven to not signed wrap
2003 // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
2004 //
2005 // For instance, this will bring two seemingly different expressions:
2006 // 1 + sext(5 + 20 * %x + 24 * %y) and
2007 // sext(6 + 20 * %x + 24 * %y)
2008 // to the same form:
2009 // 2 + sext(4 + 20 * %x + 24 * %y)
2010 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
2011 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
2012 if (D != 0) {
2013 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
2014 const SCEV *SResidual =
2015 getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth);
2016 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
2017 return getAddExpr(SSExtD, SSExtR,
2018 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
2019 Depth + 1);
2020 }
2021 }
2022 }
2023 // If the input value is a chrec scev, and we can prove that the value
2024 // did not overflow the old, smaller, value, we can sign extend all of the
2025 // operands (often constants). This allows analysis of something like
2026 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
2027 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
2028 if (AR->isAffine()) {
2029 const SCEV *Start = AR->getStart();
2030 const SCEV *Step = AR->getStepRecurrence(*this);
2031 unsigned BitWidth = getTypeSizeInBits(AR->getType());
2032 const Loop *L = AR->getLoop();
2033
2034 if (!AR->hasNoSignedWrap()) {
2035 auto NewFlags = proveNoWrapViaConstantRanges(AR);
2036 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags);
2037 }
2038
2039 // If we have special knowledge that this addrec won't overflow,
2040 // we don't need to do any further analysis.
2041 if (AR->hasNoSignedWrap())
2042 return getAddRecExpr(
2043 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
2044 getSignExtendExpr(Step, Ty, Depth + 1), L, SCEV::FlagNSW);
2045
2046 // Check whether the backedge-taken count is SCEVCouldNotCompute.
2047 // Note that this serves two purposes: It filters out loops that are
2048 // simply not analyzable, and it covers the case where this code is
2049 // being called from within backedge-taken count analysis, such that
2050 // attempting to ask for the backedge-taken count would likely result
2051 // in infinite recursion. In the later case, the analysis code will
2052 // cope with a conservative value, and it will take care to purge
2053 // that value once it has finished.
2054 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
2055 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
2056 // Manually compute the final value for AR, checking for
2057 // overflow.
2058
2059 // Check whether the backedge-taken count can be losslessly casted to
2060 // the addrec's type. The count is always unsigned.
2061 const SCEV *CastedMaxBECount =
2062 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth);
2063 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend(
2064 CastedMaxBECount, MaxBECount->getType(), Depth);
2065 if (MaxBECount == RecastedMaxBECount) {
2066 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
2067 // Check whether Start+Step*MaxBECount has no signed overflow.
2068 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step,
2069 SCEV::FlagAnyWrap, Depth + 1);
2070 const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul,
2071 SCEV::FlagAnyWrap,
2072 Depth + 1),
2073 WideTy, Depth + 1);
2074 const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1);
2075 const SCEV *WideMaxBECount =
2076 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
2077 const SCEV *OperandExtendedAdd =
2078 getAddExpr(WideStart,
2079 getMulExpr(WideMaxBECount,
2080 getSignExtendExpr(Step, WideTy, Depth + 1),
2081 SCEV::FlagAnyWrap, Depth + 1),
2082 SCEV::FlagAnyWrap, Depth + 1);
2083 if (SAdd == OperandExtendedAdd) {
2084 // Cache knowledge of AR NSW, which is propagated to this AddRec.
2085 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
2086 // Return the expression with the addrec on the outside.
2087 return getAddRecExpr(
2088 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
2089 Depth + 1),
2090 getSignExtendExpr(Step, Ty, Depth + 1), L,
2091 AR->getNoWrapFlags());
2092 }
2093 // Similar to above, only this time treat the step value as unsigned.
2094 // This covers loops that count up with an unsigned step.
2095 OperandExtendedAdd =
2096 getAddExpr(WideStart,
2097 getMulExpr(WideMaxBECount,
2098 getZeroExtendExpr(Step, WideTy, Depth + 1),
2099 SCEV::FlagAnyWrap, Depth + 1),
2100 SCEV::FlagAnyWrap, Depth + 1);
2101 if (SAdd == OperandExtendedAdd) {
2102 // If AR wraps around then
2103 //
2104 // abs(Step) * MaxBECount > unsigned-max(AR->getType())
2105 // => SAdd != OperandExtendedAdd
2106 //
2107 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=>
2108 // (SAdd == OperandExtendedAdd => AR is NW)
2109
2110 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
2111
2112 // Return the expression with the addrec on the outside.
2113 return getAddRecExpr(
2114 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
2115 Depth + 1),
2116 getZeroExtendExpr(Step, Ty, Depth + 1), L,
2117 AR->getNoWrapFlags());
2118 }
2119 }
2120 }
2121
2122 // Normally, in the cases we can prove no-overflow via a
2123 // backedge guarding condition, we can also compute a backedge
2124 // taken count for the loop. The exceptions are assumptions and
2125 // guards present in the loop -- SCEV is not great at exploiting
2126 // these to compute max backedge taken counts, but can still use
2127 // these to prove lack of overflow. Use this fact to avoid
2128 // doing extra work that may not pay off.
2129
2130 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
2131 !AC.assumptions().empty()) {
2132 // If the backedge is guarded by a comparison with the pre-inc
2133 // value the addrec is safe. Also, if the entry is guarded by
2134 // a comparison with the start value and the backedge is
2135 // guarded by a comparison with the post-inc value, the addrec
2136 // is safe.
2137 ICmpInst::Predicate Pred;
2138 const SCEV *OverflowLimit =
2139 getSignedOverflowLimitForStep(Step, &Pred, this);
2140 if (OverflowLimit &&
2141 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
2142 isKnownOnEveryIteration(Pred, AR, OverflowLimit))) {
2143 // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec.
2144 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
2145 return getAddRecExpr(
2146 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
2147 getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
2148 }
2149 }
2150
2151 // sext({C,+,Step}) --> (sext(D) + sext({C-D,+,Step}))<nuw><nsw>
2152 // if D + (C - D + Step * n) could be proven to not signed wrap
2153 // where D maximizes the number of trailing zeros of (C - D + Step * n)
2154 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
2155 const APInt &C = SC->getAPInt();
2156 const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
2157 if (D != 0) {
2158 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
2159 const SCEV *SResidual =
2160 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
2161 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
2162 return getAddExpr(SSExtD, SSExtR,
2163 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
2164 Depth + 1);
2165 }
2166 }
2167
2168 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) {
2169 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
2170 return getAddRecExpr(
2171 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
2172 getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
2173 }
2174 }
2175
2176 // If the input value is provably positive and we could not simplify
2177 // away the sext build a zext instead.
2178 if (isKnownNonNegative(Op))
2179 return getZeroExtendExpr(Op, Ty, Depth + 1);
2180
2181 // The cast wasn't folded; create an explicit cast node.
2182 // Recompute the insert position, as it may have been invalidated.
2183 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2184 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
2185 Op, Ty);
2186 UniqueSCEVs.InsertNode(S, IP);
2187 addToLoopUseLists(S);
2188 return S;
2189}
2190
2191/// getAnyExtendExpr - Return a SCEV for the given operand extended with
2192/// unspecified bits out to the given type.
2193const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
2194 Type *Ty) {
2195 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
2196 "This is not an extending conversion!");
2197 assert(isSCEVable(Ty) &&
2198 "This is not a conversion to a SCEVable type!");
2199 Ty = getEffectiveSCEVType(Ty);
2200
2201 // Sign-extend negative constants.
2202 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
2203 if (SC->getAPInt().isNegative())
2204 return getSignExtendExpr(Op, Ty);
2205
2206 // Peel off a truncate cast.
2207 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
2208 const SCEV *NewOp = T->getOperand();
2209 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
2210 return getAnyExtendExpr(NewOp, Ty);
2211 return getTruncateOrNoop(NewOp, Ty);
2212 }
2213
2214 // Next try a zext cast. If the cast is folded, use it.
2215 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
2216 if (!isa<SCEVZeroExtendExpr>(ZExt))
2217 return ZExt;
2218
2219 // Next try a sext cast. If the cast is folded, use it.
2220 const SCEV *SExt = getSignExtendExpr(Op, Ty);
2221 if (!isa<SCEVSignExtendExpr>(SExt))
2222 return SExt;
2223
2224 // Force the cast to be folded into the operands of an addrec.
2225 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
2226 SmallVector<const SCEV *, 4> Ops;
2227 for (const SCEV *Op : AR->operands())
2228 Ops.push_back(getAnyExtendExpr(Op, Ty));
2229 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
2230 }
2231
2232 // If the expression is obviously signed, use the sext cast value.
2233 if (isa<SCEVSMaxExpr>(Op))
2234 return SExt;
2235
2236 // Absent any other information, use the zext cast value.
2237 return ZExt;
2238}
2239
2240/// Process the given Ops list, which is a list of operands to be added under
2241/// the given scale, update the given map. This is a helper function for
2242/// getAddRecExpr. As an example of what it does, given a sequence of operands
2243/// that would form an add expression like this:
2244///
2245/// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
2246///
2247/// where A and B are constants, update the map with these values:
2248///
2249/// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
2250///
2251/// and add 13 + A*B*29 to AccumulatedConstant.
2252/// This will allow getAddRecExpr to produce this:
2253///
2254/// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
2255///
2256/// This form often exposes folding opportunities that are hidden in
2257/// the original operand list.
2258///
2259/// Return true iff it appears that any interesting folding opportunities
2260/// may be exposed. This helps getAddRecExpr short-circuit extra work in
2261/// the common case where no interesting opportunities are present, and
2262/// is also used as a check to avoid infinite recursion.
2263static bool
2264CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
2265 SmallVectorImpl<const SCEV *> &NewOps,
2266 APInt &AccumulatedConstant,
2267 const SCEV *const *Ops, size_t NumOperands,
2268 const APInt &Scale,
2269 ScalarEvolution &SE) {
2270 bool Interesting = false;
2271
2272 // Iterate over the add operands. They are sorted, with constants first.
2273 unsigned i = 0;
2274 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2275 ++i;
2276 // Pull a buried constant out to the outside.
2277 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
2278 Interesting = true;
2279 AccumulatedConstant += Scale * C->getAPInt();
2280 }
2281
2282 // Next comes everything else. We're especially interested in multiplies
2283 // here, but they're in the middle, so just visit the rest with one loop.
2284 for (; i != NumOperands; ++i) {
2285 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
2286 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
2287 APInt NewScale =
2288 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt();
2289 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
2290 // A multiplication of a constant with another add; recurse.
2291 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
2292 Interesting |=
2293 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2294 Add->op_begin(), Add->getNumOperands(),
2295 NewScale, SE);
2296 } else {
2297 // A multiplication of a constant with some other value. Update
2298 // the map.
2299 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
2300 const SCEV *Key = SE.getMulExpr(MulOps);
2301 auto Pair = M.insert({Key, NewScale});
2302 if (Pair.second) {
2303 NewOps.push_back(Pair.first->first);
2304 } else {
2305 Pair.first->second += NewScale;
2306 // The map already had an entry for this value, which may indicate
2307 // a folding opportunity.
2308 Interesting = true;
2309 }
2310 }
2311 } else {
2312 // An ordinary operand. Update the map.
2313 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
2314 M.insert({Ops[i], Scale});
2315 if (Pair.second) {
2316 NewOps.push_back(Pair.first->first);
2317 } else {
2318 Pair.first->second += Scale;
2319 // The map already had an entry for this value, which may indicate
2320 // a folding opportunity.
2321 Interesting = true;
2322 }
2323 }
2324 }
2325
2326 return Interesting;
2327}
2328
2329// We're trying to construct a SCEV of type `Type' with `Ops' as operands and
2330// `OldFlags' as can't-wrap behavior. Infer a more aggressive set of
2331// can't-overflow flags for the operation if possible.
2332static SCEV::NoWrapFlags
2333StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type,
2334 const ArrayRef<const SCEV *> Ops,
2335 SCEV::NoWrapFlags Flags) {
2336 using namespace std::placeholders;
2337
2338 using OBO = OverflowingBinaryOperator;
2339
2340 bool CanAnalyze =
2341 Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr;
2342 (void)CanAnalyze;
2343 assert(CanAnalyze && "don't call from other places!");
2344
2345 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
2346 SCEV::NoWrapFlags SignOrUnsignWrap =
2347 ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2348
2349 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
2350 auto IsKnownNonNegative = [&](const SCEV *S) {
2351 return SE->isKnownNonNegative(S);
2352 };
2353
2354 if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative))
2355 Flags =
2356 ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
2357
2358 SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2359
2360 if (SignOrUnsignWrap != SignOrUnsignMask &&
2361 (Type == scAddExpr || Type == scMulExpr) && Ops.size() == 2 &&
2362 isa<SCEVConstant>(Ops[0])) {
2363
2364 auto Opcode = [&] {
2365 switch (Type) {
2366 case scAddExpr:
2367 return Instruction::Add;
2368 case scMulExpr:
2369 return Instruction::Mul;
2370 default:
2371 llvm_unreachable("Unexpected SCEV op.");
2372 }
2373 }();
2374
2375 const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt();
2376
2377 // (A <opcode> C) --> (A <opcode> C)<nsw> if the op doesn't sign overflow.
2378 if (!(SignOrUnsignWrap & SCEV::FlagNSW)) {
2379 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2380 Opcode, C, OBO::NoSignedWrap);
2381 if (NSWRegion.contains(SE->getSignedRange(Ops[1])))
2382 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
2383 }
2384
2385 // (A <opcode> C) --> (A <opcode> C)<nuw> if the op doesn't unsign overflow.
2386 if (!(SignOrUnsignWrap & SCEV::FlagNUW)) {
2387 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2388 Opcode, C, OBO::NoUnsignedWrap);
2389 if (NUWRegion.contains(SE->getUnsignedRange(Ops[1])))
2390 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2391 }
2392 }
2393
2394 return Flags;
2395}
2396
2397bool ScalarEvolution::isAvailableAtLoopEntry(const SCEV *S, const Loop *L) {
2398 return isLoopInvariant(S, L) && properlyDominates(S, L->getHeader());
2399}
2400
2401/// Get a canonical add expression, or something simpler if possible.
2402const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
2403 SCEV::NoWrapFlags Flags,
2404 unsigned Depth) {
2405 assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
2406 "only nuw or nsw allowed");
2407 assert(!Ops.empty() && "Cannot get empty add!");
2408 if (Ops.size() == 1) return Ops[0];
2409#ifndef NDEBUG
2410 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2411 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2412 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2413 "SCEVAddExpr operand types don't match!");
2414#endif
2415
2416 // Sort by complexity, this groups all similar expression types together.
2417 GroupByComplexity(Ops, &LI, DT);
2418
2419 Flags = StrengthenNoWrapFlags(this, scAddExpr, Ops, Flags);
2420
2421 // If there are any constants, fold them together.
2422 unsigned Idx = 0;
2423 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2424 ++Idx;
2425 assert(Idx < Ops.size());
2426 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2427 // We found two constants, fold them together!
2428 Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt());
2429 if (Ops.size() == 2) return Ops[0];
2430 Ops.erase(Ops.begin()+1); // Erase the folded element
2431 LHSC = cast<SCEVConstant>(Ops[0]);
2432 }
2433
2434 // If we are left with a constant zero being added, strip it off.
2435 if (LHSC->getValue()->isZero()) {
2436 Ops.erase(Ops.begin());
2437 --Idx;
2438 }
2439
2440 if (Ops.size() == 1) return Ops[0];
2441 }
2442
2443 // Limit recursion calls depth.
2444 if (Depth > MaxArithDepth || hasHugeExpression(Ops))
2445 return getOrCreateAddExpr(Ops, Flags);
2446
2447 // Okay, check to see if the same value occurs in the operand list more than
2448 // once. If so, merge them together into an multiply expression. Since we
2449 // sorted the list, these values are required to be adjacent.
2450 Type *Ty = Ops[0]->getType();
2451 bool FoundMatch = false;
2452 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
2453 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
2454 // Scan ahead to count how many equal operands there are.
2455 unsigned Count = 2;
2456 while (i+Count != e && Ops[i+Count] == Ops[i])
2457 ++Count;
2458 // Merge the values into a multiply.
2459 const SCEV *Scale = getConstant(Ty, Count);
2460 const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1);
2461 if (Ops.size() == Count)
2462 return Mul;
2463 Ops[i] = Mul;
2464 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
2465 --i; e -= Count - 1;
2466 FoundMatch = true;
2467 }
2468 if (FoundMatch)
2469 return getAddExpr(Ops, Flags, Depth + 1);
2470
2471 // Check for truncates. If all the operands are truncated from the same
2472 // type, see if factoring out the truncate would permit the result to be
2473 // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y)
2474 // if the contents of the resulting outer trunc fold to something simple.
2475 auto FindTruncSrcType = [&]() -> Type * {
2476 // We're ultimately looking to fold an addrec of truncs and muls of only
2477 // constants and truncs, so if we find any other types of SCEV
2478 // as operands of the addrec then we bail and return nullptr here.
2479 // Otherwise, we return the type of the operand of a trunc that we find.
2480 if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx]))
2481 return T->getOperand()->getType();
2482 if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2483 const auto *LastOp = Mul->getOperand(Mul->getNumOperands() - 1);
2484 if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp))
2485 return T->getOperand()->getType();
2486 }
2487 return nullptr;
2488 };
2489 if (auto *SrcType = FindTruncSrcType()) {
2490 SmallVector<const SCEV *, 8> LargeOps;
2491 bool Ok = true;
2492 // Check all the operands to see if they can be represented in the
2493 // source type of the truncate.
2494 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
2495 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
2496 if (T->getOperand()->getType() != SrcType) {
2497 Ok = false;
2498 break;
2499 }
2500 LargeOps.push_back(T->getOperand());
2501 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2502 LargeOps.push_back(getAnyExtendExpr(C, SrcType));
2503 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
2504 SmallVector<const SCEV *, 8> LargeMulOps;
2505 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
2506 if (const SCEVTruncateExpr *T =
2507 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
2508 if (T->getOperand()->getType() != SrcType) {
2509 Ok = false;
2510 break;
2511 }
2512 LargeMulOps.push_back(T->getOperand());
2513 } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) {
2514 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
2515 } else {
2516 Ok = false;
2517 break;
2518 }
2519 }
2520 if (Ok)
2521 LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1));
2522 } else {
2523 Ok = false;
2524 break;
2525 }
2526 }
2527 if (Ok) {
2528 // Evaluate the expression in the larger type.
2529 const SCEV *Fold = getAddExpr(LargeOps, SCEV::FlagAnyWrap, Depth + 1);
2530 // If it folds to something simple, use it. Otherwise, don't.
2531 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
2532 return getTruncateExpr(Fold, Ty);
2533 }
2534 }
2535
2536 // Skip past any other cast SCEVs.
2537 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
2538 ++Idx;
2539
2540 // If there are add operands they would be next.
2541 if (Idx < Ops.size()) {
2542 bool DeletedAdd = false;
2543 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
2544 if (Ops.size() > AddOpsInlineThreshold ||
2545 Add->getNumOperands() > AddOpsInlineThreshold)
2546 break;
2547 // If we have an add, expand the add operands onto the end of the operands
2548 // list.
2549 Ops.erase(Ops.begin()+Idx);
2550 Ops.append(Add->op_begin(), Add->op_end());
2551 DeletedAdd = true;
2552 }
2553
2554 // If we deleted at least one add, we added operands to the end of the list,
2555 // and they are not necessarily sorted. Recurse to resort and resimplify
2556 // any operands we just acquired.
2557 if (DeletedAdd)
2558 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2559 }
2560
2561 // Skip over the add expression until we get to a multiply.
2562 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2563 ++Idx;
2564
2565 // Check to see if there are any folding opportunities present with
2566 // operands multiplied by constant values.
2567 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
2568 uint64_t BitWidth = getTypeSizeInBits(Ty);
2569 DenseMap<const SCEV *, APInt> M;
2570 SmallVector<const SCEV *, 8> NewOps;
2571 APInt AccumulatedConstant(BitWidth, 0);
2572 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2573 Ops.data(), Ops.size(),
2574 APInt(BitWidth, 1), *this)) {
2575 struct APIntCompare {
2576 bool operator()(const APInt &LHS, const APInt &RHS) const {
2577 return LHS.ult(RHS);
2578 }
2579 };
2580
2581 // Some interesting folding opportunity is present, so its worthwhile to
2582 // re-generate the operands list. Group the operands by constant scale,
2583 // to avoid multiplying by the same constant scale multiple times.
2584 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
2585 for (const SCEV *NewOp : NewOps)
2586 MulOpLists[M.find(NewOp)->second].push_back(NewOp);
2587 // Re-generate the operands list.
2588 Ops.clear();
2589 if (AccumulatedConstant != 0)
2590 Ops.push_back(getConstant(AccumulatedConstant));
2591 for (auto &MulOp : MulOpLists)
2592 if (MulOp.first != 0)
2593 Ops.push_back(getMulExpr(
2594 getConstant(MulOp.first),
2595 getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1),
2596 SCEV::FlagAnyWrap, Depth + 1));
2597 if (Ops.empty())
2598 return getZero(Ty);
2599 if (Ops.size() == 1)
2600 return Ops[0];
2601 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2602 }
2603 }
2604
2605 // If we are adding something to a multiply expression, make sure the
2606 // something is not already an operand of the multiply. If so, merge it into
2607 // the multiply.
2608 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
2609 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
2610 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
2611 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
2612 if (isa<SCEVConstant>(MulOpSCEV))
2613 continue;
2614 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
2615 if (MulOpSCEV == Ops[AddOp]) {
2616 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
2617 const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
2618 if (Mul->getNumOperands() != 2) {
2619 // If the multiply has more than two operands, we must get the
2620 // Y*Z term.
2621 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2622 Mul->op_begin()+MulOp);
2623 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2624 InnerMul = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2625 }
2626 SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul};
2627 const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2628 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV,
2629 SCEV::FlagAnyWrap, Depth + 1);
2630 if (Ops.size() == 2) return OuterMul;
2631 if (AddOp < Idx) {
2632 Ops.erase(Ops.begin()+AddOp);
2633 Ops.erase(Ops.begin()+Idx-1);
2634 } else {
2635 Ops.erase(Ops.begin()+Idx);
2636 Ops.erase(Ops.begin()+AddOp-1);
2637 }
2638 Ops.push_back(OuterMul);
2639 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2640 }
2641
2642 // Check this multiply against other multiplies being added together.
2643 for (unsigned OtherMulIdx = Idx+1;
2644 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
2645 ++OtherMulIdx) {
2646 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
2647 // If MulOp occurs in OtherMul, we can fold the two multiplies
2648 // together.
2649 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
2650 OMulOp != e; ++OMulOp)
2651 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
2652 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
2653 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
2654 if (Mul->getNumOperands() != 2) {
2655 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2656 Mul->op_begin()+MulOp);
2657 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2658 InnerMul1 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2659 }
2660 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
2661 if (OtherMul->getNumOperands() != 2) {
2662 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
2663 OtherMul->op_begin()+OMulOp);
2664 MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end());
2665 InnerMul2 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2666 }
2667 SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2};
2668 const SCEV *InnerMulSum =
2669 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2670 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum,
2671 SCEV::FlagAnyWrap, Depth + 1);
2672 if (Ops.size() == 2) return OuterMul;
2673 Ops.erase(Ops.begin()+Idx);
2674 Ops.erase(Ops.begin()+OtherMulIdx-1);
2675 Ops.push_back(OuterMul);
2676 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2677 }
2678 }
2679 }
2680 }
2681
2682 // If there are any add recurrences in the operands list, see if any other
2683 // added values are loop invariant. If so, we can fold them into the
2684 // recurrence.
2685 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2686 ++Idx;
2687
2688 // Scan over all recurrences, trying to fold loop invariants into them.
2689 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2690 // Scan all of the other operands to this add and add them to the vector if
2691 // they are loop invariant w.r.t. the recurrence.
2692 SmallVector<const SCEV *, 8> LIOps;
2693 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2694 const Loop *AddRecLoop = AddRec->getLoop();
2695 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2696 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
2697 LIOps.push_back(Ops[i]);
2698 Ops.erase(Ops.begin()+i);
2699 --i; --e;
2700 }
2701
2702 // If we found some loop invariants, fold them into the recurrence.
2703 if (!LIOps.empty()) {
2704 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
2705 LIOps.push_back(AddRec->getStart());
2706
2707 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
2708 AddRec->op_end());
2709 // This follows from the fact that the no-wrap flags on the outer add
2710 // expression are applicable on the 0th iteration, when the add recurrence
2711 // will be equal to its start value.
2712 AddRecOps[0] = getAddExpr(LIOps, Flags, Depth + 1);
2713
2714 // Build the new addrec. Propagate the NUW and NSW flags if both the
2715 // outer add and the inner addrec are guaranteed to have no overflow.
2716 // Always propagate NW.
2717 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
2718 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
2719
2720 // If all of the other operands were loop invariant, we are done.
2721 if (Ops.size() == 1) return NewRec;
2722
2723 // Otherwise, add the folded AddRec by the non-invariant parts.
2724 for (unsigned i = 0;; ++i)
2725 if (Ops[i] == AddRec) {
2726 Ops[i] = NewRec;
2727 break;
2728 }
2729 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2730 }
2731
2732 // Okay, if there weren't any loop invariants to be folded, check to see if
2733 // there are multiple AddRec's with the same loop induction variable being
2734 // added together. If so, we can fold them.
2735 for (unsigned OtherIdx = Idx+1;
2736 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2737 ++OtherIdx) {
2738 // We expect the AddRecExpr's to be sorted in reverse dominance order,
2739 // so that the 1st found AddRecExpr is dominated by all others.
2740 assert(DT.dominates(
2741 cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(),
2742 AddRec->getLoop()->getHeader()) &&
2743 "AddRecExprs are not sorted in reverse dominance order?");
2744 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
2745 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L>
2746 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
2747 AddRec->op_end());
2748 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2749 ++OtherIdx) {
2750 const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2751 if (OtherAddRec->getLoop() == AddRecLoop) {
2752 for (unsigned i = 0, e = OtherAddRec->getNumOperands();
2753 i != e; ++i) {
2754 if (i >= AddRecOps.size()) {
2755 AddRecOps.append(OtherAddRec->op_begin()+i,
2756 OtherAddRec->op_end());
2757 break;
2758 }
2759 SmallVector<const SCEV *, 2> TwoOps = {
2760 AddRecOps[i], OtherAddRec->getOperand(i)};
2761 AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2762 }
2763 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2764 }
2765 }
2766 // Step size has changed, so we cannot guarantee no self-wraparound.
2767 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
2768 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2769 }
2770 }
2771
2772 // Otherwise couldn't fold anything into this recurrence. Move onto the
2773 // next one.
2774 }
2775
2776 // Okay, it looks like we really DO need an add expr. Check to see if we
2777 // already have one, otherwise create a new one.
2778 return getOrCreateAddExpr(Ops, Flags);
2779}
2780
2781const SCEV *
2782ScalarEvolution::getOrCreateAddExpr(ArrayRef<const SCEV *> Ops,
2783 SCEV::NoWrapFlags Flags) {
2784 FoldingSetNodeID ID;
2785 ID.AddInteger(scAddExpr);
2786 for (const SCEV *Op : Ops)
2787 ID.AddPointer(Op);
2788 void *IP = nullptr;
2789 SCEVAddExpr *S =
2790 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2791 if (!S) {
2792 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2793 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2794 S = new (SCEVAllocator)
2795 SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size());
2796 UniqueSCEVs.InsertNode(S, IP);
2797 addToLoopUseLists(S);
2798 }
2799 S->setNoWrapFlags(Flags);
2800 return S;
2801}
2802
2803const SCEV *
2804ScalarEvolution::getOrCreateAddRecExpr(ArrayRef<const SCEV *> Ops,
2805 const Loop *L, SCEV::NoWrapFlags Flags) {
2806 FoldingSetNodeID ID;
2807 ID.AddInteger(scAddRecExpr);
2808 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2809 ID.AddPointer(Ops[i]);
2810 ID.AddPointer(L);
2811 void *IP = nullptr;
2812 SCEVAddRecExpr *S =
2813 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2814 if (!S) {
2815 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2816 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2817 S = new (SCEVAllocator)
2818 SCEVAddRecExpr(ID.Intern(SCEVAllocator), O, Ops.size(), L);
2819 UniqueSCEVs.InsertNode(S, IP);
2820 addToLoopUseLists(S);
2821 }
2822 S->setNoWrapFlags(Flags);
2823 return S;
2824}
2825
2826const SCEV *
2827ScalarEvolution::getOrCreateMulExpr(ArrayRef<const SCEV *> Ops,
2828 SCEV::NoWrapFlags Flags) {
2829 FoldingSetNodeID ID;
2830 ID.AddInteger(scMulExpr);
2831 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2832 ID.AddPointer(Ops[i]);
2833 void *IP = nullptr;
2834 SCEVMulExpr *S =
2835 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2836 if (!S) {
2837 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2838 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2839 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
2840 O, Ops.size());
2841 UniqueSCEVs.InsertNode(S, IP);
2842 addToLoopUseLists(S);
2843 }
2844 S->setNoWrapFlags(Flags);
2845 return S;
2846}
2847
2848static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
2849 uint64_t k = i*j;
2850 if (j > 1 && k / j != i) Overflow = true;
2851 return k;
2852}
2853
2854/// Compute the result of "n choose k", the binomial coefficient. If an
2855/// intermediate computation overflows, Overflow will be set and the return will
2856/// be garbage. Overflow is not cleared on absence of overflow.
2857static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
2858 // We use the multiplicative formula:
2859 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
2860 // At each iteration, we take the n-th term of the numeral and divide by the
2861 // (k-n)th term of the denominator. This division will always produce an
2862 // integral result, and helps reduce the chance of overflow in the
2863 // intermediate computations. However, we can still overflow even when the
2864 // final result would fit.
2865
2866 if (n == 0 || n == k) return 1;
2867 if (k > n) return 0;
2868
2869 if (k > n/2)
2870 k = n-k;
2871
2872 uint64_t r = 1;
2873 for (uint64_t i = 1; i <= k; ++i) {
2874 r = umul_ov(r, n-(i-1), Overflow);
2875 r /= i;
2876 }
2877 return r;
2878}
2879
2880/// Determine if any of the operands in this SCEV are a constant or if
2881/// any of the add or multiply expressions in this SCEV contain a constant.
2882static bool containsConstantInAddMulChain(const SCEV *StartExpr) {
2883 struct FindConstantInAddMulChain {
2884 bool FoundConstant = false;
2885
2886 bool follow(const SCEV *S) {
2887 FoundConstant |= isa<SCEVConstant>(S);
2888 return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S);
2889 }
2890
2891 bool isDone() const {
2892 return FoundConstant;
2893 }
2894 };
2895
2896 FindConstantInAddMulChain F;
2897 SCEVTraversal<FindConstantInAddMulChain> ST(F);
2898 ST.visitAll(StartExpr);
2899 return F.FoundConstant;
2900}
2901
2902/// Get a canonical multiply expression, or something simpler if possible.
2903const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
2904 SCEV::NoWrapFlags Flags,
2905 unsigned Depth) {
2906 assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) &&
2907 "only nuw or nsw allowed");
2908 assert(!Ops.empty() && "Cannot get empty mul!");
2909 if (Ops.size() == 1) return Ops[0];
2910#ifndef NDEBUG
2911 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2912 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2913 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2914 "SCEVMulExpr operand types don't match!");
2915#endif
2916
2917 // Sort by complexity, this groups all similar expression types together.
2918 GroupByComplexity(Ops, &LI, DT);
2919
2920 Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags);
2921
2922 // Limit recursion calls depth.
2923 if (Depth > MaxArithDepth || hasHugeExpression(Ops))
2924 return getOrCreateMulExpr(Ops, Flags);
2925
2926 // If there are any constants, fold them together.
2927 unsigned Idx = 0;
2928 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2929
2930 if (Ops.size() == 2)
2931 // C1*(C2+V) -> C1*C2 + C1*V
2932 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
2933 // If any of Add's ops are Adds or Muls with a constant, apply this
2934 // transformation as well.
2935 //
2936 // TODO: There are some cases where this transformation is not
2937 // profitable; for example, Add = (C0 + X) * Y + Z. Maybe the scope of
2938 // this transformation should be narrowed down.
2939 if (Add->getNumOperands() == 2 && containsConstantInAddMulChain(Add))
2940 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0),
2941 SCEV::FlagAnyWrap, Depth + 1),
2942 getMulExpr(LHSC, Add->getOperand(1),
2943 SCEV::FlagAnyWrap, Depth + 1),
2944 SCEV::FlagAnyWrap, Depth + 1);
2945
2946 ++Idx;
2947 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2948 // We found two constants, fold them together!
2949 ConstantInt *Fold =
2950 ConstantInt::get(getContext(), LHSC->getAPInt() * RHSC->getAPInt());
2951 Ops[0] = getConstant(Fold);
2952 Ops.erase(Ops.begin()+1); // Erase the folded element
2953 if (Ops.size() == 1) return Ops[0];
2954 LHSC = cast<SCEVConstant>(Ops[0]);
2955 }
2956
2957 // If we are left with a constant one being multiplied, strip it off.
2958 if (cast<SCEVConstant>(Ops[0])->getValue()->isOne()) {
2959 Ops.erase(Ops.begin());
2960 --Idx;
2961 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
2962 // If we have a multiply of zero, it will always be zero.
2963 return Ops[0];
2964 } else if (Ops[0]->isAllOnesValue()) {
2965 // If we have a mul by -1 of an add, try distributing the -1 among the
2966 // add operands.
2967 if (Ops.size() == 2) {
2968 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
2969 SmallVector<const SCEV *, 4> NewOps;
2970 bool AnyFolded = false;
2971 for (const SCEV *AddOp : Add->operands()) {
2972 const SCEV *Mul = getMulExpr(Ops[0], AddOp, SCEV::FlagAnyWrap,
2973 Depth + 1);
2974 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
2975 NewOps.push_back(Mul);
2976 }
2977 if (AnyFolded)
2978 return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1);
2979 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
2980 // Negation preserves a recurrence's no self-wrap property.
2981 SmallVector<const SCEV *, 4> Operands;
2982 for (const SCEV *AddRecOp : AddRec->operands())
2983 Operands.push_back(getMulExpr(Ops[0], AddRecOp, SCEV::FlagAnyWrap,
2984 Depth + 1));
2985
2986 return getAddRecExpr(Operands, AddRec->getLoop(),
2987 AddRec->getNoWrapFlags(SCEV::FlagNW));
2988 }
2989 }
2990 }
2991
2992 if (Ops.size() == 1)
2993 return Ops[0];
2994 }
2995
2996 // Skip over the add expression until we get to a multiply.
2997 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2998 ++Idx;
2999
3000 // If there are mul operands inline them all into this expression.
3001 if (Idx < Ops.size()) {
3002 bool DeletedMul = false;
3003 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
3004 if (Ops.size() > MulOpsInlineThreshold)
3005 break;
3006 // If we have an mul, expand the mul operands onto the end of the
3007 // operands list.
3008 Ops.erase(Ops.begin()+Idx);
3009 Ops.append(Mul->op_begin(), Mul->op_end());
3010 DeletedMul = true;
3011 }
3012
3013 // If we deleted at least one mul, we added operands to the end of the
3014 // list, and they are not necessarily sorted. Recurse to resort and
3015 // resimplify any operands we just acquired.
3016 if (DeletedMul)
3017 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3018 }
3019
3020 // If there are any add recurrences in the operands list, see if any other
3021 // added values are loop invariant. If so, we can fold them into the
3022 // recurrence.
3023 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
3024 ++Idx;
3025
3026 // Scan over all recurrences, trying to fold loop invariants into them.
3027 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
3028 // Scan all of the other operands to this mul and add them to the vector
3029 // if they are loop invariant w.r.t. the recurrence.
3030 SmallVector<const SCEV *, 8> LIOps;
3031 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
3032 const Loop *AddRecLoop = AddRec->getLoop();
3033 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3034 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
3035 LIOps.push_back(Ops[i]);
3036 Ops.erase(Ops.begin()+i);
3037 --i; --e;
3038 }
3039
3040 // If we found some loop invariants, fold them into the recurrence.
3041 if (!LIOps.empty()) {
3042 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
3043 SmallVector<const SCEV *, 4> NewOps;
3044 NewOps.reserve(AddRec->getNumOperands());
3045 const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1);
3046 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
3047 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i),
3048 SCEV::FlagAnyWrap, Depth + 1));
3049
3050 // Build the new addrec. Propagate the NUW and NSW flags if both the
3051 // outer mul and the inner addrec are guaranteed to have no overflow.
3052 //
3053 // No self-wrap cannot be guaranteed after changing the step size, but
3054 // will be inferred if either NUW or NSW is true.
3055 Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW));
3056 const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags);
3057
3058 // If all of the other operands were loop invariant, we are done.
3059 if (Ops.size() == 1) return NewRec;
3060
3061 // Otherwise, multiply the folded AddRec by the non-invariant parts.
3062 for (unsigned i = 0;; ++i)
3063 if (Ops[i] == AddRec) {
3064 Ops[i] = NewRec;
3065 break;
3066 }
3067 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3068 }
3069
3070 // Okay, if there weren't any loop invariants to be folded, check to see
3071 // if there are multiple AddRec's with the same loop induction variable
3072 // being multiplied together. If so, we can fold them.
3073
3074 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
3075 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
3076 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
3077 // ]]],+,...up to x=2n}.
3078 // Note that the arguments to choose() are always integers with values
3079 // known at compile time, never SCEV objects.
3080 //
3081 // The implementation avoids pointless extra computations when the two
3082 // addrec's are of different length (mathematically, it's equivalent to
3083 // an infinite stream of zeros on the right).
3084 bool OpsModified = false;
3085 for (unsigned OtherIdx = Idx+1;
3086 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
3087 ++OtherIdx) {
3088 const SCEVAddRecExpr *OtherAddRec =
3089 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
3090 if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop)
3091 continue;
3092
3093 // Limit max number of arguments to avoid creation of unreasonably big
3094 // SCEVAddRecs with very complex operands.
3095 if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 >
3096 MaxAddRecSize || isHugeExpression(AddRec) ||
3097 isHugeExpression(OtherAddRec))
3098 continue;
3099
3100 bool Overflow = false;
3101 Type *Ty = AddRec->getType();
3102 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
3103 SmallVector<const SCEV*, 7> AddRecOps;
3104 for (int x = 0, xe = AddRec->getNumOperands() +
3105 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
3106 SmallVector <const SCEV *, 7> SumOps;
3107 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
3108 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
3109 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
3110 ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
3111 z < ze && !Overflow; ++z) {
3112 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
3113 uint64_t Coeff;
3114 if (LargerThan64Bits)
3115 Coeff = umul_ov(Coeff1, Coeff2, Overflow);
3116 else
3117 Coeff = Coeff1*Coeff2;
3118 const SCEV *CoeffTerm = getConstant(Ty, Coeff);
3119 const SCEV *Term1 = AddRec->getOperand(y-z);
3120 const SCEV *Term2 = OtherAddRec->getOperand(z);
3121 SumOps.push_back(getMulExpr(CoeffTerm, Term1, Term2,
3122 SCEV::FlagAnyWrap, Depth + 1));
3123 }
3124 }
3125 if (SumOps.empty())
3126 SumOps.push_back(getZero(Ty));
3127 AddRecOps.push_back(getAddExpr(SumOps, SCEV::FlagAnyWrap, Depth + 1));
3128 }
3129 if (!Overflow) {
3130 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRecLoop,
3131 SCEV::FlagAnyWrap);
3132 if (Ops.size() == 2) return NewAddRec;
3133 Ops[Idx] = NewAddRec;
3134 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
3135 OpsModified = true;
3136 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
3137 if (!AddRec)
3138 break;
3139 }
3140 }
3141 if (OpsModified)
3142 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3143
3144 // Otherwise couldn't fold anything into this recurrence. Move onto the
3145 // next one.
3146 }
3147
3148 // Okay, it looks like we really DO need an mul expr. Check to see if we
3149 // already have one, otherwise create a new one.
3150 return getOrCreateMulExpr(Ops, Flags);
3151}
3152
3153/// Represents an unsigned remainder expression based on unsigned division.
3154const SCEV *ScalarEvolution::getURemExpr(const SCEV *LHS,
3155 const SCEV *RHS) {
3156 assert(getEffectiveSCEVType(LHS->getType()) ==
3157 getEffectiveSCEVType(RHS->getType()) &&
3158 "SCEVURemExpr operand types don't match!");
3159
3160 // Short-circuit easy cases
3161 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3162 // If constant is one, the result is trivial
3163 if (RHSC->getValue()->isOne())
3164 return getZero(LHS->getType()); // X urem 1 --> 0
3165
3166 // If constant is a power of two, fold into a zext(trunc(LHS)).
3167 if (RHSC->getAPInt().isPowerOf2()) {
3168 Type *FullTy = LHS->getType();
3169 Type *TruncTy =
3170 IntegerType::get(getContext(), RHSC->getAPInt().logBase2());
3171 return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy);
3172 }
3173 }
3174
3175 // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y)
3176 const SCEV *UDiv = getUDivExpr(LHS, RHS);
3177 const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW);
3178 return getMinusSCEV(LHS, Mult, SCEV::FlagNUW);
3179}
3180
3181/// Get a canonical unsigned division expression, or something simpler if
3182/// possible.
3183const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
3184 const SCEV *RHS) {
3185 assert(getEffectiveSCEVType(LHS->getType()) ==
3186 getEffectiveSCEVType(RHS->getType()) &&
3187 "SCEVUDivExpr operand types don't match!");
3188
3189 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3190 if (RHSC->getValue()->isOne())
3191 return LHS; // X udiv 1 --> x
3192 // If the denominator is zero, the result of the udiv is undefined. Don't
3193 // try to analyze it, because the resolution chosen here may differ from
3194 // the resolution chosen in other parts of the compiler.
3195 if (!RHSC->getValue()->isZero()) {
3196 // Determine if the division can be folded into the operands of
3197 // its operands.
3198 // TODO: Generalize this to non-constants by using known-bits information.
3199 Type *Ty = LHS->getType();
3200 unsigned LZ = RHSC->getAPInt().countLeadingZeros();
3201 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
3202 // For non-power-of-two values, effectively round the value up to the
3203 // nearest power of two.
3204 if (!RHSC->getAPInt().isPowerOf2())
3205 ++MaxShiftAmt;
3206 IntegerType *ExtTy =
3207 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
3208 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
3209 if (const SCEVConstant *Step =
3210 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
3211 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
3212 const APInt &StepInt = Step->getAPInt();
3213 const APInt &DivInt = RHSC->getAPInt();
3214 if (!StepInt.urem(DivInt) &&
3215 getZeroExtendExpr(AR, ExtTy) ==
3216 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3217 getZeroExtendExpr(Step, ExtTy),
3218 AR->getLoop(), SCEV::FlagAnyWrap)) {
3219 SmallVector<const SCEV *, 4> Operands;
3220 for (const SCEV *Op : AR->operands())
3221 Operands.push_back(getUDivExpr(Op, RHS));
3222 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW);
3223 }
3224 /// Get a canonical UDivExpr for a recurrence.
3225 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
3226 // We can currently only fold X%N if X is constant.
3227 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart());
3228 if (StartC && !DivInt.urem(StepInt) &&
3229 getZeroExtendExpr(AR, ExtTy) ==
3230 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3231 getZeroExtendExpr(Step, ExtTy),
3232 AR->getLoop(), SCEV::FlagAnyWrap)) {
3233 const APInt &StartInt = StartC->getAPInt();
3234 const APInt &StartRem = StartInt.urem(StepInt);
3235 if (StartRem != 0)
3236 LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step,
3237 AR->getLoop(), SCEV::FlagNW);
3238 }
3239 }
3240 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
3241 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
3242 SmallVector<const SCEV *, 4> Operands;
3243 for (const SCEV *Op : M->operands())
3244 Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3245 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
3246 // Find an operand that's safely divisible.
3247 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
3248 const SCEV *Op = M->getOperand(i);
3249 const SCEV *Div = getUDivExpr(Op, RHSC);
3250 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
3251 Operands = SmallVector<const SCEV *, 4>(M->op_begin(),
3252 M->op_end());
3253 Operands[i] = Div;
3254 return getMulExpr(Operands);
3255 }
3256 }
3257 }
3258
3259 // (A/B)/C --> A/(B*C) if safe and B*C can be folded.
3260 if (const SCEVUDivExpr *OtherDiv = dyn_cast<SCEVUDivExpr>(LHS)) {
3261 if (auto *DivisorConstant =
3262 dyn_cast<SCEVConstant>(OtherDiv->getRHS())) {
3263 bool Overflow = false;
3264 APInt NewRHS =
3265 DivisorConstant->getAPInt().umul_ov(RHSC->getAPInt(), Overflow);
3266 if (Overflow) {
3267 return getConstant(RHSC->getType(), 0, false);
3268 }
3269 return getUDivExpr(OtherDiv->getLHS(), getConstant(NewRHS));
3270 }
3271 }
3272
3273 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
3274 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
3275 SmallVector<const SCEV *, 4> Operands;
3276 for (const SCEV *Op : A->operands())
3277 Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3278 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
3279 Operands.clear();
3280 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
3281 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
3282 if (isa<SCEVUDivExpr>(Op) ||
3283 getMulExpr(Op, RHS) != A->getOperand(i))
3284 break;
3285 Operands.push_back(Op);
3286 }
3287 if (Operands.size() == A->getNumOperands())
3288 return getAddExpr(Operands);
3289 }
3290 }
3291
3292 // Fold if both operands are constant.
3293 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
3294 Constant *LHSCV = LHSC->getValue();
3295 Constant *RHSCV = RHSC->getValue();
3296 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
3297 RHSCV)));
3298 }
3299 }
3300 }
3301
3302 FoldingSetNodeID ID;
3303 ID.AddInteger(scUDivExpr);
3304 ID.AddPointer(LHS);
3305 ID.AddPointer(RHS);
3306 void *IP = nullptr;
3307 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3308 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
3309 LHS, RHS);
3310 UniqueSCEVs.InsertNode(S, IP);
3311 addToLoopUseLists(S);
3312 return S;
3313}
3314
3315static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) {
3316 APInt A = C1->getAPInt().abs();
3317 APInt B = C2->getAPInt().abs();
3318 uint32_t ABW = A.getBitWidth();
3319 uint32_t BBW = B.getBitWidth();
3320
3321 if (ABW > BBW)
3322 B = B.zext(ABW);
3323 else if (ABW < BBW)
3324 A = A.zext(BBW);
3325
3326 return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B));
3327}
3328
3329/// Get a canonical unsigned division expression, or something simpler if
3330/// possible. There is no representation for an exact udiv in SCEV IR, but we
3331/// can attempt to remove factors from the LHS and RHS. We can't do this when
3332/// it's not exact because the udiv may be clearing bits.
3333const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS,
3334 const SCEV *RHS) {
3335 // TODO: we could try to find factors in all sorts of things, but for now we
3336 // just deal with u/exact (multiply, constant). See SCEVDivision towards the
3337 // end of this file for inspiration.
3338
3339 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS);
3340 if (!Mul || !Mul->hasNoUnsignedWrap())
3341 return getUDivExpr(LHS, RHS);
3342
3343 if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) {
3344 // If the mulexpr multiplies by a constant, then that constant must be the
3345 // first element of the mulexpr.
3346 if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
3347 if (LHSCst == RHSCst) {
3348 SmallVector<const SCEV *, 2> Operands;
3349 Operands.append(Mul->op_begin() + 1, Mul->op_end());
3350 return getMulExpr(Operands);
3351 }
3352
3353 // We can't just assume that LHSCst divides RHSCst cleanly, it could be
3354 // that there's a factor provided by one of the other terms. We need to
3355 // check.
3356 APInt Factor = gcd(LHSCst, RHSCst);
3357 if (!Factor.isIntN(1)) {
3358 LHSCst =
3359 cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor)));
3360 RHSCst =
3361 cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor)));
3362 SmallVector<const SCEV *, 2> Operands;
3363 Operands.push_back(LHSCst);
3364 Operands.append(Mul->op_begin() + 1, Mul->op_end());
3365 LHS = getMulExpr(Operands);
3366 RHS = RHSCst;
3367 Mul = dyn_cast<SCEVMulExpr>(LHS);
3368 if (!Mul)
3369 return getUDivExactExpr(LHS, RHS);
3370 }
3371 }
3372 }
3373
3374 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
3375 if (Mul->getOperand(i) == RHS) {
3376 SmallVector<const SCEV *, 2> Operands;
3377 Operands.append(Mul->op_begin(), Mul->op_begin() + i);
3378 Operands.append(Mul->op_begin() + i + 1, Mul->op_end());
3379 return getMulExpr(Operands);
3380 }
3381 }
3382
3383 return getUDivExpr(LHS, RHS);
3384}
3385
3386/// Get an add recurrence expression for the specified loop. Simplify the
3387/// expression as much as possible.
3388const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step,
3389 const Loop *L,
3390 SCEV::NoWrapFlags Flags) {
3391 SmallVector<const SCEV *, 4> Operands;
3392 Operands.push_back(Start);
3393 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
3394 if (StepChrec->getLoop() == L) {
3395 Operands.append(StepChrec->op_begin(), StepChrec->op_end());
3396 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW));
3397 }
3398
3399 Operands.push_back(Step);
3400 return getAddRecExpr(Operands, L, Flags);
3401}
3402
3403/// Get an add recurrence expression for the specified loop. Simplify the
3404/// expression as much as possible.
3405const SCEV *
3406ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
3407 const Loop *L, SCEV::NoWrapFlags Flags) {
3408 if (Operands.size() == 1) return Operands[0];
3409#ifndef NDEBUG
3410 Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
3411 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
3412 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy &&
3413 "SCEVAddRecExpr operand types don't match!");
3414 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
3415 assert(isLoopInvariant(Operands[i], L) &&
3416 "SCEVAddRecExpr operand is not loop-invariant!");
3417#endif
3418
3419 if (Operands.back()->isZero()) {
3420 Operands.pop_back();
3421 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X
3422 }
3423
3424 // It's tempting to want to call getMaxBackedgeTakenCount count here and
3425 // use that information to infer NUW and NSW flags. However, computing a
3426 // BE count requires calling getAddRecExpr, so we may not yet have a
3427 // meaningful BE count at this point (and if we don't, we'd be stuck
3428 // with a SCEVCouldNotCompute as the cached BE count).
3429
3430 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
3431
3432 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
3433 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
3434 const Loop *NestedLoop = NestedAR->getLoop();
3435 if (L->contains(NestedLoop)
3436 ? (L->getLoopDepth() < NestedLoop->getLoopDepth())
3437 : (!NestedLoop->contains(L) &&
3438 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) {
3439 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
3440 NestedAR->op_end());
3441 Operands[0] = NestedAR->getStart();
3442 // AddRecs require their operands be loop-invariant with respect to their
3443 // loops. Don't perform this transformation if it would break this
3444 // requirement.
3445 bool AllInvariant = all_of(
3446 Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); });
3447
3448 if (AllInvariant) {
3449 // Create a recurrence for the outer loop with the same step size.
3450 //
3451 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
3452 // inner recurrence has the same property.
3453 SCEV::NoWrapFlags OuterFlags =
3454 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
3455
3456 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
3457 AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) {
3458 return isLoopInvariant(Op, NestedLoop);
3459 });
3460
3461 if (AllInvariant) {
3462 // Ok, both add recurrences are valid after the transformation.
3463 //
3464 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
3465 // the outer recurrence has the same property.
3466 SCEV::NoWrapFlags InnerFlags =
3467 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
3468 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
3469 }
3470 }
3471 // Reset Operands to its original state.
3472 Operands[0] = NestedAR;
3473 }
3474 }
3475
3476 // Okay, it looks like we really DO need an addrec expr. Check to see if we
3477 // already have one, otherwise create a new one.
3478 return getOrCreateAddRecExpr(Operands, L, Flags);
3479}
3480
3481const SCEV *
3482ScalarEvolution::getGEPExpr(GEPOperator *GEP,
3483 const SmallVectorImpl<const SCEV *> &IndexExprs) {
3484 const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand());
3485 // getSCEV(Base)->getType() has the same address space as Base->getType()
3486 // because SCEV::getType() preserves the address space.
3487 Type *IntPtrTy = getEffectiveSCEVType(BaseExpr->getType());
3488 // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP
3489 // instruction to its SCEV, because the Instruction may be guarded by control
3490 // flow and the no-overflow bits may not be valid for the expression in any
3491 // context. This can be fixed similarly to how these flags are handled for
3492 // adds.
3493 SCEV::NoWrapFlags Wrap = GEP->isInBounds() ? SCEV::FlagNSW
3494 : SCEV::FlagAnyWrap;
3495
3496 const SCEV *TotalOffset = getZero(IntPtrTy);
3497 // The array size is unimportant. The first thing we do on CurTy is getting
3498 // its element type.
3499 Type *CurTy = ArrayType::get(GEP->getSourceElementType(), 0);
3500 for (const SCEV *IndexExpr : IndexExprs) {
3501 // Compute the (potentially symbolic) offset in bytes for this index.
3502 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
3503 // For a struct, add the member offset.
3504 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue();
3505 unsigned FieldNo = Index->getZExtValue();
3506 const SCEV *FieldOffset = getOffsetOfExpr(IntPtrTy, STy, FieldNo);
3507
3508 // Add the field offset to the running total offset.
3509 TotalOffset = getAddExpr(TotalOffset, FieldOffset);
3510
3511 // Update CurTy to the type of the field at Index.
3512 CurTy = STy->getTypeAtIndex(Index);
3513 } else {
3514 // Update CurTy to its element type.
3515 CurTy = cast<SequentialType>(CurTy)->getElementType();
3516 // For an array, add the element offset, explicitly scaled.
3517 const SCEV *ElementSize = getSizeOfExpr(IntPtrTy, CurTy);
3518 // Getelementptr indices are signed.
3519 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntPtrTy);
3520
3521 // Multiply the index by the element size to compute the element offset.
3522 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap);
3523
3524 // Add the element offset to the running total offset.
3525 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
3526 }
3527 }
3528
3529 // Add the total offset from all the GEP indices to the base.
3530 return getAddExpr(BaseExpr, TotalOffset, Wrap);
3531}
3532
3533std::tuple<const SCEV *, FoldingSetNodeID, void *>
3534ScalarEvolution::findExistingSCEVInCache(int SCEVType,
3535 ArrayRef<const SCEV *> Ops) {
3536 FoldingSetNodeID ID;
3537 void *IP = nullptr;
3538 ID.AddInteger(SCEVType);
3539 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3540 ID.AddPointer(Ops[i]);
3541 return std::tuple<const SCEV *, FoldingSetNodeID, void *>(
3542 UniqueSCEVs.FindNodeOrInsertPos(ID, IP), std::move(ID), IP);
3543}
3544
3545const SCEV *ScalarEvolution::getMinMaxExpr(unsigned Kind,
3546 SmallVectorImpl<const SCEV *> &Ops) {
3547 assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!");
3548 if (Ops.size() == 1) return Ops[0];
3549#ifndef NDEBUG
3550 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3551 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3552 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
3553 "Operand types don't match!");
3554#endif
3555
3556 bool IsSigned = Kind == scSMaxExpr || Kind == scSMinExpr;
3557 bool IsMax = Kind == scSMaxExpr || Kind == scUMaxExpr;
3558
3559 // Sort by complexity, this groups all similar expression types together.
3560 GroupByComplexity(Ops, &LI, DT);
3561
3562 // Check if we have created the same expression before.
3563 if (const SCEV *S = std::get<0>(findExistingSCEVInCache(Kind, Ops))) {
3564 return S;
3565 }
3566
3567 // If there are any constants, fold them together.
3568 unsigned Idx = 0;
3569 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3570 ++Idx;
3571 assert(Idx < Ops.size());
3572 auto FoldOp = [&](const APInt &LHS, const APInt &RHS) {
3573 if (Kind == scSMaxExpr)
3574 return APIntOps::smax(LHS, RHS);
3575 else if (Kind == scSMinExpr)
3576 return APIntOps::smin(LHS, RHS);
3577 else if (Kind == scUMaxExpr)
3578 return APIntOps::umax(LHS, RHS);
3579 else if (Kind == scUMinExpr)
3580 return APIntOps::umin(LHS, RHS);
3581 llvm_unreachable("Unknown SCEV min/max opcode");
3582 };
3583
3584 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3585 // We found two constants, fold them together!
3586 ConstantInt *Fold = ConstantInt::get(
3587 getContext(), FoldOp(LHSC->getAPInt(), RHSC->getAPInt()));
3588 Ops[0] = getConstant(Fold);
3589 Ops.erase(Ops.begin()+1); // Erase the folded element
3590 if (Ops.size() == 1) return Ops[0];
3591 LHSC = cast<SCEVConstant>(Ops[0]);
3592 }
3593
3594 bool IsMinV = LHSC->getValue()->isMinValue(IsSigned);
3595 bool IsMaxV = LHSC->getValue()->isMaxValue(IsSigned);
3596
3597 if (IsMax ? IsMinV : IsMaxV) {
3598 // If we are left with a constant minimum(/maximum)-int, strip it off.
3599 Ops.erase(Ops.begin());
3600 --Idx;
3601 } else if (IsMax ? IsMaxV : IsMinV) {
3602 // If we have a max(/min) with a constant maximum(/minimum)-int,
3603 // it will always be the extremum.
3604 return LHSC;
3605 }
3606
3607 if (Ops.size() == 1) return Ops[0];
3608 }
3609
3610 // Find the first operation of the same kind
3611 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < Kind)
3612 ++Idx;
3613
3614 // Check to see if one of the operands is of the same kind. If so, expand its
3615 // operands onto our operand list, and recurse to simplify.
3616 if (Idx < Ops.size()) {
3617 bool DeletedAny = false;
3618 while (Ops[Idx]->getSCEVType() == Kind) {
3619 const SCEVMinMaxExpr *SMME = cast<SCEVMinMaxExpr>(Ops[Idx]);
3620 Ops.erase(Ops.begin()+Idx);
3621 Ops.append(SMME->op_begin(), SMME->op_end());
3622 DeletedAny = true;
3623 }
3624
3625 if (DeletedAny)
3626 return getMinMaxExpr(Kind, Ops);
3627 }
3628
3629 // Okay, check to see if the same value occurs in the operand list twice. If
3630 // so, delete one. Since we sorted the list, these values are required to
3631 // be adjacent.
3632 llvm::CmpInst::Predicate GEPred =
3633 IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
3634 llvm::CmpInst::Predicate LEPred =
3635 IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
3636 llvm::CmpInst::Predicate FirstPred = IsMax ? GEPred : LEPred;
3637 llvm::CmpInst::Predicate SecondPred = IsMax ? LEPred : GEPred;
3638 for (unsigned i = 0, e = Ops.size() - 1; i != e; ++i) {
3639 if (Ops[i] == Ops[i + 1] ||
3640 isKnownViaNonRecursiveReasoning(FirstPred, Ops[i], Ops[i + 1])) {
3641 // X op Y op Y --> X op Y
3642 // X op Y --> X, if we know X, Y are ordered appropriately
3643 Ops.erase(Ops.begin() + i + 1, Ops.begin() + i + 2);
3644 --i;
3645 --e;
3646 } else if (isKnownViaNonRecursiveReasoning(SecondPred, Ops[i],
3647 Ops[i + 1])) {
3648 // X op Y --> Y, if we know X, Y are ordered appropriately
3649 Ops.erase(Ops.begin() + i, Ops.begin() + i + 1);
3650 --i;
3651 --e;
3652 }
3653 }
3654
3655 if (Ops.size() == 1) return Ops[0];
3656
3657 assert(!Ops.empty() && "Reduced smax down to nothing!");
3658
3659 // Okay, it looks like we really DO need an expr. Check to see if we
3660 // already have one, otherwise create a new one.
3661 const SCEV *ExistingSCEV;
3662 FoldingSetNodeID ID;
3663 void *IP;
3664 std::tie(ExistingSCEV, ID, IP) = findExistingSCEVInCache(Kind, Ops);
3665 if (ExistingSCEV)
3666 return ExistingSCEV;
3667 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3668 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3669 SCEV *S = new (SCEVAllocator) SCEVMinMaxExpr(
3670 ID.Intern(SCEVAllocator), static_cast<SCEVTypes>(Kind), O, Ops.size());
3671
3672 UniqueSCEVs.InsertNode(S, IP);
3673 addToLoopUseLists(S);
3674 return S;
3675}
3676
3677const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, const SCEV *RHS) {
3678 SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
3679 return getSMaxExpr(Ops);
3680}
3681
3682const SCEV *ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
3683 return getMinMaxExpr(scSMaxExpr, Ops);
3684}
3685
3686const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, const SCEV *RHS) {
3687 SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
3688 return getUMaxExpr(Ops);
3689}
3690
3691const SCEV *ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
3692 return getMinMaxExpr(scUMaxExpr, Ops);
3693}
3694
3695const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
3696 const SCEV *RHS) {
3697 SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
3698 return getSMinExpr(Ops);
3699}
3700
3701const SCEV *ScalarEvolution::getSMinExpr(SmallVectorImpl<const SCEV *> &Ops) {
3702 return getMinMaxExpr(scSMinExpr, Ops);
3703}
3704
3705const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
3706 const SCEV *RHS) {
3707 SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
3708 return getUMinExpr(Ops);
3709}
3710
3711const SCEV *ScalarEvolution::getUMinExpr(SmallVectorImpl<const SCEV *> &Ops) {
3712 return getMinMaxExpr(scUMinExpr, Ops);
3713}
3714
3715const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) {
3716 // We can bypass creating a target-independent
3717 // constant expression and then folding it back into a ConstantInt.
3718 // This is just a compile-time optimization.
3719 return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy));
3720}
3721
3722const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy,
3723 StructType *STy,
3724 unsigned FieldNo) {
3725 // We can bypass creating a target-independent
3726 // constant expression and then folding it back into a ConstantInt.
3727 // This is just a compile-time optimization.
3728 return getConstant(
3729 IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo));
3730}
3731
3732const SCEV *ScalarEvolution::getUnknown(Value *V) {
3733 // Don't attempt to do anything other than create a SCEVUnknown object
3734 // here. createSCEV only calls getUnknown after checking for all other
3735 // interesting possibilities, and any other code that calls getUnknown
3736 // is doing so in order to hide a value from SCEV canonicalization.
3737
3738 FoldingSetNodeID ID;
3739 ID.AddInteger(scUnknown);
3740 ID.AddPointer(V);
3741 void *IP = nullptr;
3742 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
3743 assert(cast<SCEVUnknown>(S)->getValue() == V &&
3744 "Stale SCEVUnknown in uniquing map!");
3745 return S;
3746 }
3747 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
3748 FirstUnknown);
3749 FirstUnknown = cast<SCEVUnknown>(S);
3750 UniqueSCEVs.InsertNode(S, IP);
3751 return S;
3752}
3753
3754//===----------------------------------------------------------------------===//
3755// Basic SCEV Analysis and PHI Idiom Recognition Code
3756//
3757
3758/// Test if values of the given type are analyzable within the SCEV
3759/// framework. This primarily includes integer types, and it can optionally
3760/// include pointer types if the ScalarEvolution class has access to
3761/// target-specific information.
3762bool ScalarEvolution::isSCEVable(Type *Ty) const {
3763 // Integers and pointers are always SCEVable.
3764 return Ty->isIntOrPtrTy();
3765}
3766
3767/// Return the size in bits of the specified type, for which isSCEVable must
3768/// return true.
3769uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const {
3770 assert(isSCEVable(Ty) && "Type is not SCEVable!");
3771 if (Ty->isPointerTy())
3772 return getDataLayout().getIndexTypeSizeInBits(Ty);
3773 return getDataLayout().getTypeSizeInBits(Ty);
3774}
3775
3776/// Return a type with the same bitwidth as the given type and which represents
3777/// how SCEV will treat the given type, for which isSCEVable must return
3778/// true. For pointer types, this is the pointer-sized integer type.
3779Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const {
3780 assert(isSCEVable(Ty) && "Type is not SCEVable!");
3781
3782 if (Ty->isIntegerTy())
3783 return Ty;
3784
3785 // The only other support type is pointer.
3786 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
3787 return getDataLayout().getIntPtrType(Ty);
3788}
3789
3790Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const {
3791 return getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2;
3792}
3793
3794const SCEV *ScalarEvolution::getCouldNotCompute() {
3795 return CouldNotCompute.get();
3796}
3797
3798bool ScalarEvolution::checkValidity(const SCEV *S) const {
3799 bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) {
3800 auto *SU = dyn_cast<SCEVUnknown>(S);
3801 return SU && SU->getValue() == nullptr;
3802 });
3803
3804 return !ContainsNulls;
3805}
3806
3807bool ScalarEvolution::containsAddRecurrence(const SCEV *S) {
3808 HasRecMapType::iterator I = HasRecMap.find(S);
3809 if (I != HasRecMap.end())
3810 return I->second;
3811
3812 bool FoundAddRec = SCEVExprContains(S, isa<SCEVAddRecExpr, const SCEV *>);
3813 HasRecMap.insert({S, FoundAddRec});
3814 return FoundAddRec;
3815}
3816
3817/// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}.
3818/// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an
3819/// offset I, then return {S', I}, else return {\p S, nullptr}.
3820static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) {
3821 const auto *Add = dyn_cast<SCEVAddExpr>(S);
3822 if (!Add)
3823 return {S, nullptr};
3824
3825 if (Add->getNumOperands() != 2)
3826 return {S, nullptr};
3827
3828 auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0));
3829 if (!ConstOp)
3830 return {S, nullptr};
3831
3832 return {Add->getOperand(1), ConstOp->getValue()};
3833}
3834
3835/// Return the ValueOffsetPair set for \p S. \p S can be represented
3836/// by the value and offset from any ValueOffsetPair in the set.
3837SetVector<ScalarEvolution::ValueOffsetPair> *
3838ScalarEvolution::getSCEVValues(const SCEV *S) {
3839 ExprValueMapType::iterator SI = ExprValueMap.find_as(S);
3840 if (SI == ExprValueMap.end())
3841 return nullptr;
3842#ifndef NDEBUG
3843 if (VerifySCEVMap) {
3844 // Check there is no dangling Value in the set returned.
3845 for (const auto &VE : SI->second)
3846 assert(ValueExprMap.count(VE.first));
3847 }
3848#endif
3849 return &SI->second;
3850}
3851
3852/// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V)
3853/// cannot be used separately. eraseValueFromMap should be used to remove
3854/// V from ValueExprMap and ExprValueMap at the same time.
3855void ScalarEvolution::eraseValueFromMap(Value *V) {
3856 ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3857 if (I != ValueExprMap.end()) {
3858 const SCEV *S = I->second;
3859 // Remove {V, 0} from the set of ExprValueMap[S]
3860 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(S))
3861 SV->remove({V, nullptr});
3862
3863 // Remove {V, Offset} from the set of ExprValueMap[Stripped]
3864 const SCEV *Stripped;
3865 ConstantInt *Offset;
3866 std::tie(Stripped, Offset) = splitAddExpr(S);
3867 if (Offset != nullptr) {
3868 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(Stripped))
3869 SV->remove({V, Offset});
3870 }
3871 ValueExprMap.erase(V);
3872 }
3873}
3874
3875/// Check whether value has nuw/nsw/exact set but SCEV does not.
3876/// TODO: In reality it is better to check the poison recursively
3877/// but this is better than nothing.
3878static bool SCEVLostPoisonFlags(const SCEV *S, const Value *V) {
3879 if (auto *I = dyn_cast<Instruction>(V)) {
3880 if (isa<OverflowingBinaryOperator>(I)) {
3881 if (auto *NS = dyn_cast<SCEVNAryExpr>(S)) {
3882 if (I->hasNoSignedWrap() && !NS->hasNoSignedWrap())
3883 return true;
3884 if (I->hasNoUnsignedWrap() && !NS->hasNoUnsignedWrap())
3885 return true;
3886 }
3887 } else if (isa<PossiblyExactOperator>(I) && I->isExact())
3888 return true;
3889 }
3890 return false;
3891}
3892
3893/// Return an existing SCEV if it exists, otherwise analyze the expression and
3894/// create a new one.
3895const SCEV *ScalarEvolution::getSCEV(Value *V) {
3896 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
3897
3898 const SCEV *S = getExistingSCEV(V);
3899 if (S == nullptr) {
3900 S = createSCEV(V);
3901 // During PHI resolution, it is possible to create two SCEVs for the same
3902 // V, so it is needed to double check whether V->S is inserted into
3903 // ValueExprMap before insert S->{V, 0} into ExprValueMap.
3904 std::pair<ValueExprMapType::iterator, bool> Pair =
3905 ValueExprMap.insert({SCEVCallbackVH(V, this), S});
3906 if (Pair.second && !SCEVLostPoisonFlags(S, V)) {
3907 ExprValueMap[S].insert({V, nullptr});
3908
3909 // If S == Stripped + Offset, add Stripped -> {V, Offset} into
3910 // ExprValueMap.
3911 const SCEV *Stripped = S;
3912 ConstantInt *Offset = nullptr;
3913 std::tie(Stripped, Offset) = splitAddExpr(S);
3914 // If stripped is SCEVUnknown, don't bother to save
3915 // Stripped -> {V, offset}. It doesn't simplify and sometimes even
3916 // increase the complexity of the expansion code.
3917 // If V is GetElementPtrInst, don't save Stripped -> {V, offset}
3918 // because it may generate add/sub instead of GEP in SCEV expansion.
3919 if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) &&
3920 !isa<GetElementPtrInst>(V))
3921 ExprValueMap[Stripped].insert({V, Offset});
3922 }
3923 }
3924 return S;
3925}
3926
3927const SCEV *ScalarEvolution::getExistingSCEV(Value *V) {
3928 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
3929
3930 ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3931 if (I != ValueExprMap.end()) {
3932 const SCEV *S = I->second;
3933 if (checkValidity(S))
3934 return S;
3935 eraseValueFromMap(V);
3936 forgetMemoizedResults(S);
3937 }
3938 return nullptr;
3939}
3940
3941/// Return a SCEV corresponding to -V = -1*V
3942const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V,
3943 SCEV::NoWrapFlags Flags) {
3944 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
3945 return getConstant(
3946 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
3947
3948 Type *Ty = V->getType();
3949 Ty = getEffectiveSCEVType(Ty);
3950 return getMulExpr(
3951 V, getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))), Flags);
3952}
3953
3954/// If Expr computes ~A, return A else return nullptr
3955static const SCEV *MatchNotExpr(const SCEV *Expr) {
3956 const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr);
3957 if (!Add || Add->getNumOperands() != 2 ||
3958 !Add->getOperand(0)->isAllOnesValue())
3959 return nullptr;
3960
3961 const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1));
3962 if (!AddRHS || AddRHS->getNumOperands() != 2 ||
3963 !AddRHS->getOperand(0)->isAllOnesValue())
3964 return nullptr;
3965
3966 return AddRHS->getOperand(1);
3967}
3968
3969/// Return a SCEV corresponding to ~V = -1-V
3970const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
3971 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
3972 return getConstant(
3973 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
3974
3975 // Fold ~(u|s)(min|max)(~x, ~y) to (u|s)(max|min)(x, y)
3976 if (const SCEVMinMaxExpr *MME = dyn_cast<SCEVMinMaxExpr>(V)) {
3977 auto MatchMinMaxNegation = [&](const SCEVMinMaxExpr *MME) {
3978 SmallVector<const SCEV *, 2> MatchedOperands;
3979 for (const SCEV *Operand : MME->operands()) {
3980 const SCEV *Matched = MatchNotExpr(Operand);
3981 if (!Matched)
3982 return (const SCEV *)nullptr;
3983 MatchedOperands.push_back(Matched);
3984 }
3985 return getMinMaxExpr(
3986 SCEVMinMaxExpr::negate(static_cast<SCEVTypes>(MME->getSCEVType())),
3987 MatchedOperands);
3988 };
3989 if (const SCEV *Replaced = MatchMinMaxNegation(MME))
3990 return Replaced;
3991 }
3992
3993 Type *Ty = V->getType();
3994 Ty = getEffectiveSCEVType(Ty);
3995 const SCEV *AllOnes =
3996 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
3997 return getMinusSCEV(AllOnes, V);
3998}
3999
4000const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
4001 SCEV::NoWrapFlags Flags,
4002 unsigned Depth) {
4003 // Fast path: X - X --> 0.
4004 if (LHS == RHS)
4005 return getZero(LHS->getType());
4006
4007 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation
4008 // makes it so that we cannot make much use of NUW.
4009 auto AddFlags = SCEV::FlagAnyWrap;
4010 const bool RHSIsNotMinSigned =
4011 !getSignedRangeMin(RHS).isMinSignedValue();
4012 if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) {
4013 // Let M be the minimum representable signed value. Then (-1)*RHS
4014 // signed-wraps if and only if RHS is M. That can happen even for
4015 // a NSW subtraction because e.g. (-1)*M signed-wraps even though
4016 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS +
4017 // (-1)*RHS, we need to prove that RHS != M.
4018 //
4019 // If LHS is non-negative and we know that LHS - RHS does not
4020 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap
4021 // either by proving that RHS > M or that LHS >= 0.
4022 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) {
4023 AddFlags = SCEV::FlagNSW;
4024 }
4025 }
4026
4027 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS -
4028 // RHS is NSW and LHS >= 0.
4029 //
4030 // The difficulty here is that the NSW flag may have been proven
4031 // relative to a loop that is to be found in a recurrence in LHS and
4032 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a
4033 // larger scope than intended.
4034 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
4035
4036 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth);
4037}
4038
4039const SCEV *ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty,
4040 unsigned Depth) {
4041 Type *SrcTy = V->getType();
4042 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4043 "Cannot truncate or zero extend with non-integer arguments!");
4044 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4045 return V; // No conversion
4046 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4047 return getTruncateExpr(V, Ty, Depth);
4048 return getZeroExtendExpr(V, Ty, Depth);
4049}
4050
4051const SCEV *ScalarEvolution::getTruncateOrSignExtend(const SCEV *V, Type *Ty,
4052 unsigned Depth) {
4053 Type *SrcTy = V->getType();
4054 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4055 "Cannot truncate or zero extend with non-integer arguments!");
4056 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4057 return V; // No conversion
4058 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4059 return getTruncateExpr(V, Ty, Depth);
4060 return getSignExtendExpr(V, Ty, Depth);
4061}
4062
4063const SCEV *
4064ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) {
4065 Type *SrcTy = V->getType();
4066 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4067 "Cannot noop or zero extend with non-integer arguments!");
4068 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
4069 "getNoopOrZeroExtend cannot truncate!");
4070 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4071 return V; // No conversion
4072 return getZeroExtendExpr(V, Ty);
4073}
4074
4075const SCEV *
4076ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) {
4077 Type *SrcTy = V->getType();
4078 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4079 "Cannot noop or sign extend with non-integer arguments!");
4080 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
4081 "getNoopOrSignExtend cannot truncate!");
4082 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4083 return V; // No conversion
4084 return getSignExtendExpr(V, Ty);
4085}
4086
4087const SCEV *
4088ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) {
4089 Type *SrcTy = V->getType();
4090 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4091 "Cannot noop or any extend with non-integer arguments!");
4092 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
4093 "getNoopOrAnyExtend cannot truncate!");
4094 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4095 return V; // No conversion
4096 return getAnyExtendExpr(V, Ty);
4097}
4098
4099const SCEV *
4100ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) {
4101 Type *SrcTy = V->getType();
4102 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4103 "Cannot truncate or noop with non-integer arguments!");
4104 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
4105 "getTruncateOrNoop cannot extend!");
4106 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4107 return V; // No conversion
4108 return getTruncateExpr(V, Ty);
4109}
4110
4111const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
4112 const SCEV *RHS) {
4113 const SCEV *PromotedLHS = LHS;
4114 const SCEV *PromotedRHS = RHS;
4115
4116 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
4117 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
4118 else
4119 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
4120
4121 return getUMaxExpr(PromotedLHS, PromotedRHS);
4122}
4123
4124const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
4125 const SCEV *RHS) {
4126 SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
4127 return getUMinFromMismatchedTypes(Ops);
4128}
4129
4130const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(
4131 SmallVectorImpl<const SCEV *> &Ops) {
4132 assert(!Ops.empty() && "At least one operand must be!");
4133 // Trivial case.
4134 if (Ops.size() == 1)
4135 return Ops[0];
4136
4137 // Find the max type first.
4138 Type *MaxType = nullptr;
4139 for (auto *S : Ops)
4140 if (MaxType)
4141 MaxType = getWiderType(MaxType, S->getType());
4142 else
4143 MaxType = S->getType();
4144
4145 // Extend all ops to max type.
4146 SmallVector<const SCEV *, 2> PromotedOps;
4147 for (auto *S : Ops)
4148 PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType));
4149
4150 // Generate umin.
4151 return getUMinExpr(PromotedOps);
4152}
4153
4154const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) {
4155 // A pointer operand may evaluate to a nonpointer expression, such as null.
4156 if (!V->getType()->isPointerTy())
4157 return V;
4158
4159 if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) {
4160 return getPointerBase(Cast->getOperand());
4161 } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) {
4162 const SCEV *PtrOp = nullptr;
4163 for (const SCEV *NAryOp : NAry->operands()) {
4164 if (NAryOp->getType()->isPointerTy()) {
4165 // Cannot find the base of an expression with multiple pointer operands.
4166 if (PtrOp)
4167 return V;
4168 PtrOp = NAryOp;
4169 }
4170 }
4171 if (!PtrOp)
4172 return V;
4173 return getPointerBase(PtrOp);
4174 }
4175 return V;
4176}
4177
4178/// Push users of the given Instruction onto the given Worklist.
4179static void
4180PushDefUseChildren(Instruction *I,
4181 SmallVectorImpl<Instruction *> &Worklist) {
4182 // Push the def-use children onto the Worklist stack.
4183 for (User *U : I->users())
4184 Worklist.push_back(cast<Instruction>(U));
4185}
4186
4187void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) {
4188 SmallVector<Instruction *, 16> Worklist;
4189 PushDefUseChildren(PN, Worklist);
4190
4191 SmallPtrSet<Instruction *, 8> Visited;
4192 Visited.insert(PN);
4193 while (!Worklist.empty()) {
4194 Instruction *I = Worklist.pop_back_val();
4195 if (!Visited.insert(I).second)
4196 continue;
4197
4198 auto It = ValueExprMap.find_as(static_cast<Value *>(I));
4199 if (It != ValueExprMap.end()) {
4200 const SCEV *Old = It->second;
4201
4202 // Short-circuit the def-use traversal if the symbolic name
4203 // ceases to appear in expressions.
4204 if (Old != SymName && !hasOperand(Old, SymName))
4205 continue;
4206
4207 // SCEVUnknown for a PHI either means that it has an unrecognized
4208 // structure, it's a PHI that's in the progress of being computed
4209 // by createNodeForPHI, or it's a single-value PHI. In the first case,
4210 // additional loop trip count information isn't going to change anything.
4211 // In the second case, createNodeForPHI will perform the necessary
4212 // updates on its own when it gets to that point. In the third, we do
4213 // want to forget the SCEVUnknown.
4214 if (!isa<PHINode>(I) ||
4215 !isa<SCEVUnknown>(Old) ||
4216 (I != PN && Old == SymName)) {
4217 eraseValueFromMap(It->first);
4218 forgetMemoizedResults(Old);
4219 }
4220 }
4221
4222 PushDefUseChildren(I, Worklist);
4223 }
4224}
4225
4226namespace {
4227
4228/// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start
4229/// expression in case its Loop is L. If it is not L then
4230/// if IgnoreOtherLoops is true then use AddRec itself
4231/// otherwise rewrite cannot be done.
4232/// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4233class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> {
4234public:
4235 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
4236 bool IgnoreOtherLoops = true) {
4237 SCEVInitRewriter Rewriter(L, SE);
4238 const SCEV *Result = Rewriter.visit(S);
4239 if (Rewriter.hasSeenLoopVariantSCEVUnknown())
4240 return SE.getCouldNotCompute();
4241 return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops
4242 ? SE.getCouldNotCompute()
4243 : Result;
4244 }
4245
4246 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4247 if (!SE.isLoopInvariant(Expr, L))
4248 SeenLoopVariantSCEVUnknown = true;
4249 return Expr;
4250 }
4251
4252 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4253 // Only re-write AddRecExprs for this loop.
4254 if (Expr->getLoop() == L)
4255 return Expr->getStart();
4256 SeenOtherLoops = true;
4257 return Expr;
4258 }
4259
4260 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4261
4262 bool hasSeenOtherLoops() { return SeenOtherLoops; }
4263
4264private:
4265 explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE)
4266 : SCEVRewriteVisitor(SE), L(L) {}
4267
4268 const Loop *L;
4269 bool SeenLoopVariantSCEVUnknown = false;
4270 bool SeenOtherLoops = false;
4271};
4272
4273/// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post
4274/// increment expression in case its Loop is L. If it is not L then
4275/// use AddRec itself.
4276/// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4277class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> {
4278public:
4279 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) {
4280 SCEVPostIncRewriter Rewriter(L, SE);
4281 const SCEV *Result = Rewriter.visit(S);
4282 return Rewriter.hasSeenLoopVariantSCEVUnknown()
4283 ? SE.getCouldNotCompute()
4284 : Result;
4285 }
4286
4287 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4288 if (!SE.isLoopInvariant(Expr, L))
4289 SeenLoopVariantSCEVUnknown = true;
4290 return Expr;
4291 }
4292
4293 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4294 // Only re-write AddRecExprs for this loop.
4295 if (Expr->getLoop() == L)
4296 return Expr->getPostIncExpr(SE);
4297 SeenOtherLoops = true;
4298 return Expr;
4299 }
4300
4301 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4302
4303 bool hasSeenOtherLoops() { return SeenOtherLoops; }
4304
4305private:
4306 explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE)
4307 : SCEVRewriteVisitor(SE), L(L) {}
4308
4309 const Loop *L;
4310 bool SeenLoopVariantSCEVUnknown = false;
4311 bool SeenOtherLoops = false;
4312};
4313
4314/// This class evaluates the compare condition by matching it against the
4315/// condition of loop latch. If there is a match we assume a true value
4316/// for the condition while building SCEV nodes.
4317class SCEVBackedgeConditionFolder
4318 : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> {
4319public:
4320 static const SCEV *rewrite(const SCEV *S, const Loop *L,
4321 ScalarEvolution &SE) {
4322 bool IsPosBECond = false;
4323 Value *BECond = nullptr;
4324 if (BasicBlock *Latch = L->getLoopLatch()) {
4325 BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator());
4326 if (BI && BI->isConditional()) {
4327 assert(BI->getSuccessor(0) != BI->getSuccessor(1) &&
4328 "Both outgoing branches should not target same header!");
4329 BECond = BI->getCondition();
4330 IsPosBECond = BI->getSuccessor(0) == L->getHeader();
4331 } else {
4332 return S;
4333 }
4334 }
4335 SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE);
4336 return Rewriter.visit(S);
4337 }
4338
4339 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4340 const SCEV *Result = Expr;
4341 bool InvariantF = SE.isLoopInvariant(Expr, L);
4342
4343 if (!InvariantF) {
4344 Instruction *I = cast<Instruction>(Expr->getValue());
4345 switch (I->getOpcode()) {
4346 case Instruction::Select: {
4347 SelectInst *SI = cast<SelectInst>(I);
4348 Optional<const SCEV *> Res =
4349 compareWithBackedgeCondition(SI->getCondition());
4350 if (Res.hasValue()) {
4351 bool IsOne = cast<SCEVConstant>(Res.getValue())->getValue()->isOne();
4352 Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue());
4353 }
4354 break;
4355 }
4356 default: {
4357 Optional<const SCEV *> Res = compareWithBackedgeCondition(I);
4358 if (Res.hasValue())
4359 Result = Res.getValue();
4360 break;
4361 }
4362 }
4363 }
4364 return Result;
4365 }
4366
4367private:
4368 explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond,
4369 bool IsPosBECond, ScalarEvolution &SE)
4370 : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond),
4371 IsPositiveBECond(IsPosBECond) {}
4372
4373 Optional<const SCEV *> compareWithBackedgeCondition(Value *IC);
4374
4375 const Loop *L;
4376 /// Loop back condition.
4377 Value *BackedgeCond = nullptr;
4378 /// Set to true if loop back is on positive branch condition.
4379 bool IsPositiveBECond;
4380};
4381
4382Optional<const SCEV *>
4383SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) {
4384
4385 // If value matches the backedge condition for loop latch,
4386 // then return a constant evolution node based on loopback
4387 // branch taken.
4388 if (BackedgeCond == IC)
4389 return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext()))
4390 : SE.getZero(Type::getInt1Ty(SE.getContext()));
4391 return None;
4392}
4393
4394class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> {
4395public:
4396 static const SCEV *rewrite(const SCEV *S, const Loop *L,
4397 ScalarEvolution &SE) {
4398 SCEVShiftRewriter Rewriter(L, SE);
4399 const SCEV *Result = Rewriter.visit(S);
4400 return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
4401 }
4402
4403 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4404 // Only allow AddRecExprs for this loop.
4405 if (!SE.isLoopInvariant(Expr, L))
4406 Valid = false;
4407 return Expr;
4408 }
4409
4410 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4411 if (Expr->getLoop() == L && Expr->isAffine())
4412 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE));
4413 Valid = false;
4414 return Expr;
4415 }
4416
4417 bool isValid() { return Valid; }
4418
4419private:
4420 explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE)
4421 : SCEVRewriteVisitor(SE), L(L) {}
4422
4423 const Loop *L;
4424 bool Valid = true;
4425};
4426
4427} // end anonymous namespace
4428
4429SCEV::NoWrapFlags
4430ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) {
4431 if (!AR->isAffine())
4432 return SCEV::FlagAnyWrap;
4433
4434 using OBO = OverflowingBinaryOperator;
4435
4436 SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap;
4437
4438 if (!AR->hasNoSignedWrap()) {
4439 ConstantRange AddRecRange = getSignedRange(AR);
4440 ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this));
4441
4442 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
4443 Instruction::Add, IncRange, OBO::NoSignedWrap);
4444 if (NSWRegion.contains(AddRecRange))
4445 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW);
4446 }
4447
4448 if (!AR->hasNoUnsignedWrap()) {
4449 ConstantRange AddRecRange = getUnsignedRange(AR);
4450 ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this));
4451
4452 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
4453 Instruction::Add, IncRange, OBO::NoUnsignedWrap);
4454 if (NUWRegion.contains(AddRecRange))
4455 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW);
4456 }
4457
4458 return Result;
4459}
4460
4461namespace {
4462
4463/// Represents an abstract binary operation. This may exist as a
4464/// normal instruction or constant expression, or may have been
4465/// derived from an expression tree.
4466struct BinaryOp {
4467 unsigned Opcode;
4468 Value *LHS;
4469 Value *RHS;
4470 bool IsNSW = false;
4471 bool IsNUW = false;
4472
4473 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or
4474 /// constant expression.
4475 Operator *Op = nullptr;
4476
4477 explicit BinaryOp(Operator *Op)
4478 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)),
4479 Op(Op) {
4480 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) {
4481 IsNSW = OBO->hasNoSignedWrap();
4482 IsNUW = OBO->hasNoUnsignedWrap();
4483 }
4484 }
4485
4486 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false,
4487 bool IsNUW = false)
4488 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {}
4489};
4490
4491} // end anonymous namespace
4492
4493/// Try to map \p V into a BinaryOp, and return \c None on failure.
4494static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) {
4495 auto *Op = dyn_cast<Operator>(V);
4496 if (!Op)
4497 return None;
4498
4499 // Implementation detail: all the cleverness here should happen without
4500 // creating new SCEV expressions -- our caller knowns tricks to avoid creating
4501 // SCEV expressions when possible, and we should not break that.
4502
4503 switch (Op->getOpcode()) {
4504 case Instruction::Add:
4505 case Instruction::Sub:
4506 case Instruction::Mul:
4507 case Instruction::UDiv:
4508 case Instruction::URem:
4509 case Instruction::And:
4510 case Instruction::Or:
4511 case Instruction::AShr:
4512 case Instruction::Shl:
4513 return BinaryOp(Op);
4514
4515 case Instruction::Xor:
4516 if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1)))
4517 // If the RHS of the xor is a signmask, then this is just an add.
4518 // Instcombine turns add of signmask into xor as a strength reduction step.
4519 if (RHSC->getValue().isSignMask())
4520 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
4521 return BinaryOp(Op);
4522
4523 case Instruction::LShr:
4524 // Turn logical shift right of a constant into a unsigned divide.
4525 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) {
4526 uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth();
4527
4528 // If the shift count is not less than the bitwidth, the result of
4529 // the shift is undefined. Don't try to analyze it, because the
4530 // resolution chosen here may differ from the resolution chosen in
4531 // other parts of the compiler.
4532 if (SA->getValue().ult(BitWidth)) {
4533 Constant *X =
4534 ConstantInt::get(SA->getContext(),
4535 APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
4536 return BinaryOp(Instruction::UDiv, Op->getOperand(0), X);
4537 }
4538 }
4539 return BinaryOp(Op);
4540
4541 case Instruction::ExtractValue: {
4542 auto *EVI = cast<ExtractValueInst>(Op);
4543 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0)
4544 break;
4545
4546 auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand());
4547 if (!WO)
4548 break;
4549
4550 Instruction::BinaryOps BinOp = WO->getBinaryOp();
4551 bool Signed = WO->isSigned();
4552 // TODO: Should add nuw/nsw flags for mul as well.
4553 if (BinOp == Instruction::Mul || !isOverflowIntrinsicNoWrap(WO, DT))
4554 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS());
4555
4556 // Now that we know that all uses of the arithmetic-result component of
4557 // CI are guarded by the overflow check, we can go ahead and pretend
4558 // that the arithmetic is non-overflowing.
4559 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS(),
4560 /* IsNSW = */ Signed, /* IsNUW = */ !Signed);
4561 }
4562
4563 default:
4564 break;
4565 }
4566
4567 return None;
4568}
4569
4570/// Helper function to createAddRecFromPHIWithCasts. We have a phi
4571/// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via
4572/// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the
4573/// way. This function checks if \p Op, an operand of this SCEVAddExpr,
4574/// follows one of the following patterns:
4575/// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
4576/// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
4577/// If the SCEV expression of \p Op conforms with one of the expected patterns
4578/// we return the type of the truncation operation, and indicate whether the
4579/// truncated type should be treated as signed/unsigned by setting
4580/// \p Signed to true/false, respectively.
4581static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI,
4582 bool &Signed, ScalarEvolution &SE) {
4583 // The case where Op == SymbolicPHI (that is, with no type conversions on
4584 // the way) is handled by the regular add recurrence creating logic and
4585 // would have already been triggered in createAddRecForPHI. Reaching it here
4586 // means that createAddRecFromPHI had failed for this PHI before (e.g.,
4587 // because one of the other operands of the SCEVAddExpr updating this PHI is
4588 // not invariant).
4589 //
4590 // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in
4591 // this case predicates that allow us to prove that Op == SymbolicPHI will
4592 // be added.
4593 if (Op == SymbolicPHI)
4594 return nullptr;
4595
4596 unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType());
4597 unsigned NewBits = SE.getTypeSizeInBits(Op->getType());
4598 if (SourceBits != NewBits)
4599 return nullptr;
4600
4601 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(Op);
4602 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(Op);
4603 if (!SExt && !ZExt)
4604 return nullptr;
4605 const SCEVTruncateExpr *Trunc =
4606 SExt ? dyn_cast<SCEVTruncateExpr>(SExt->getOperand())
4607 : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand());
4608 if (!Trunc)
4609 return nullptr;
4610 const SCEV *X = Trunc->getOperand();
4611 if (X != SymbolicPHI)
4612 return nullptr;
4613 Signed = SExt != nullptr;
4614 return Trunc->getType();
4615}
4616
4617static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) {
4618 if (!PN->getType()->isIntegerTy())
4619 return nullptr;
4620 const Loop *L = LI.getLoopFor(PN->getParent());
4621 if (!L || L->getHeader() != PN->getParent())
4622 return nullptr;
4623 return L;
4624}
4625
4626// Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the
4627// computation that updates the phi follows the following pattern:
4628// (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum
4629// which correspond to a phi->trunc->sext/zext->add->phi update chain.
4630// If so, try to see if it can be rewritten as an AddRecExpr under some
4631// Predicates. If successful, return them as a pair. Also cache the results
4632// of the analysis.
4633//
4634// Example usage scenario:
4635// Say the Rewriter is called for the following SCEV:
4636// 8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
4637// where:
4638// %X = phi i64 (%Start, %BEValue)
4639// It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X),
4640// and call this function with %SymbolicPHI = %X.
4641//
4642// The analysis will find that the value coming around the backedge has
4643// the following SCEV:
4644// BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
4645// Upon concluding that this matches the desired pattern, the function
4646// will return the pair {NewAddRec, SmallPredsVec} where:
4647// NewAddRec = {%Start,+,%Step}
4648// SmallPredsVec = {P1, P2, P3} as follows:
4649// P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw>
4650// P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64)
4651// P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64)
4652// The returned pair means that SymbolicPHI can be rewritten into NewAddRec
4653// under the predicates {P1,P2,P3}.
4654// This predicated rewrite will be cached in PredicatedSCEVRewrites:
4655// PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)}
4656//
4657// TODO's:
4658//
4659// 1) Extend the Induction descriptor to also support inductions that involve
4660// casts: When needed (namely, when we are called in the context of the
4661// vectorizer induction analysis), a Set of cast instructions will be
4662// populated by this method, and provided back to isInductionPHI. This is
4663// needed to allow the vectorizer to properly record them to be ignored by
4664// the cost model and to avoid vectorizing them (otherwise these casts,
4665// which are redundant under the runtime overflow checks, will be
4666// vectorized, which can be costly).
4667//
4668// 2) Support additional induction/PHISCEV patterns: We also want to support
4669// inductions where the sext-trunc / zext-trunc operations (partly) occur
4670// after the induction update operation (the induction increment):
4671//
4672// (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix)
4673// which correspond to a phi->add->trunc->sext/zext->phi update chain.
4674//
4675// (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix)
4676// which correspond to a phi->trunc->add->sext/zext->phi update chain.
4677//
4678// 3) Outline common code with createAddRecFromPHI to avoid duplication.
4679Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
4680ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) {
4681 SmallVector<const SCEVPredicate *, 3> Predicates;
4682
4683 // *** Part1: Analyze if we have a phi-with-cast pattern for which we can
4684 // return an AddRec expression under some predicate.
4685
4686 auto *PN = cast<PHINode>(SymbolicPHI->getValue());
4687 const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
4688 assert(L && "Expecting an integer loop header phi");
4689
4690 // The loop may have multiple entrances or multiple exits; we can analyze
4691 // this phi as an addrec if it has a unique entry value and a unique
4692 // backedge value.
4693 Value *BEValueV = nullptr, *StartValueV = nullptr;
4694 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
4695 Value *V = PN->getIncomingValue(i);
4696 if (L->contains(PN->getIncomingBlock(i))) {
4697 if (!BEValueV) {
4698 BEValueV = V;
4699 } else if (BEValueV != V) {
4700 BEValueV = nullptr;
4701 break;
4702 }
4703 } else if (!StartValueV) {
4704 StartValueV = V;
4705 } else if (StartValueV != V) {
4706 StartValueV = nullptr;
4707 break;
4708 }
4709 }
4710 if (!BEValueV || !StartValueV)
4711 return None;
4712
4713 const SCEV *BEValue = getSCEV(BEValueV);
4714
4715 // If the value coming around the backedge is an add with the symbolic
4716 // value we just inserted, possibly with casts that we can ignore under
4717 // an appropriate runtime guard, then we found a simple induction variable!
4718 const auto *Add = dyn_cast<SCEVAddExpr>(BEValue);
4719 if (!Add)
4720 return None;
4721
4722 // If there is a single occurrence of the symbolic value, possibly
4723 // casted, replace it with a recurrence.
4724 unsigned FoundIndex = Add->getNumOperands();
4725 Type *TruncTy = nullptr;
4726 bool Signed;
4727 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4728 if ((TruncTy =
4729 isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this)))
4730 if (FoundIndex == e) {
4731 FoundIndex = i;
4732 break;
4733 }
4734
4735 if (FoundIndex == Add->getNumOperands())
4736 return None;
4737
4738 // Create an add with everything but the specified operand.
4739 SmallVector<const SCEV *, 8> Ops;
4740 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4741 if (i != FoundIndex)
4742 Ops.push_back(Add->getOperand(i));
4743 const SCEV *Accum = getAddExpr(Ops);
4744
4745 // The runtime checks will not be valid if the step amount is
4746 // varying inside the loop.
4747 if (!isLoopInvariant(Accum, L))
4748 return None;
4749
4750 // *** Part2: Create the predicates
4751
4752 // Analysis was successful: we have a phi-with-cast pattern for which we
4753 // can return an AddRec expression under the following predicates:
4754 //
4755 // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum)
4756 // fits within the truncated type (does not overflow) for i = 0 to n-1.
4757 // P2: An Equal predicate that guarantees that
4758 // Start = (Ext ix (Trunc iy (Start) to ix) to iy)
4759 // P3: An Equal predicate that guarantees that
4760 // Accum = (Ext ix (Trunc iy (Accum) to ix) to iy)
4761 //
4762 // As we next prove, the above predicates guarantee that:
4763 // Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy)
4764 //
4765 //
4766 // More formally, we want to prove that:
4767 // Expr(i+1) = Start + (i+1) * Accum
4768 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
4769 //
4770 // Given that:
4771 // 1) Expr(0) = Start
4772 // 2) Expr(1) = Start + Accum
4773 // = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2
4774 // 3) Induction hypothesis (step i):
4775 // Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum
4776 //
4777 // Proof:
4778 // Expr(i+1) =
4779 // = Start + (i+1)*Accum
4780 // = (Start + i*Accum) + Accum
4781 // = Expr(i) + Accum
4782 // = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum
4783 // :: from step i
4784 //
4785 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum
4786 //
4787 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy)
4788 // + (Ext ix (Trunc iy (Accum) to ix) to iy)
4789 // + Accum :: from P3
4790 //
4791 // = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy)
4792 // + Accum :: from P1: Ext(x)+Ext(y)=>Ext(x+y)
4793 //
4794 // = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum
4795 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
4796 //
4797 // By induction, the same applies to all iterations 1<=i<n:
4798 //
4799
4800 // Create a truncated addrec for which we will add a no overflow check (P1).
4801 const SCEV *StartVal = getSCEV(StartValueV);
4802 const SCEV *PHISCEV =
4803 getAddRecExpr(getTruncateExpr(StartVal, TruncTy),
4804 getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap);
4805
4806 // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr.
4807 // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV
4808 // will be constant.
4809 //
4810 // If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't
4811 // add P1.
4812 if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) {
4813 SCEVWrapPredicate::IncrementWrapFlags AddedFlags =
4814 Signed ? SCEVWrapPredicate::IncrementNSSW
4815 : SCEVWrapPredicate::IncrementNUSW;
4816 const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags);
4817 Predicates.push_back(AddRecPred);
4818 }
4819
4820 // Create the Equal Predicates P2,P3:
4821
4822 // It is possible that the predicates P2 and/or P3 are computable at
4823 // compile time due to StartVal and/or Accum being constants.
4824 // If either one is, then we can check that now and escape if either P2
4825 // or P3 is false.
4826
4827 // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy)
4828 // for each of StartVal and Accum
4829 auto getExtendedExpr = [&](const SCEV *Expr,
4830 bool CreateSignExtend) -> const SCEV * {
4831 assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant");
4832 const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy);
4833 const SCEV *ExtendedExpr =
4834 CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType())
4835 : getZeroExtendExpr(TruncatedExpr, Expr->getType());
4836 return ExtendedExpr;
4837 };
4838
4839 // Given:
4840 // ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy
4841 // = getExtendedExpr(Expr)
4842 // Determine whether the predicate P: Expr == ExtendedExpr
4843 // is known to be false at compile time
4844 auto PredIsKnownFalse = [&](const SCEV *Expr,
4845 const SCEV *ExtendedExpr) -> bool {
4846 return Expr != ExtendedExpr &&
4847 isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr);
4848 };
4849
4850 const SCEV *StartExtended = getExtendedExpr(StartVal, Signed);
4851 if (PredIsKnownFalse(StartVal, StartExtended)) {
4852 LLVM_DEBUG(dbgs() << "P2 is compile-time false\n";);
4853 return None;
4854 }
4855
4856 // The Step is always Signed (because the overflow checks are either
4857 // NSSW or NUSW)
4858 const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true);
4859 if (PredIsKnownFalse(Accum, AccumExtended)) {
4860 LLVM_DEBUG(dbgs() << "P3 is compile-time false\n";);
4861 return None;
4862 }
4863
4864 auto AppendPredicate = [&](const SCEV *Expr,
4865 const SCEV *ExtendedExpr) -> void {
4866 if (Expr != ExtendedExpr &&
4867 !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) {
4868 const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr);
4869 LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred);
4870 Predicates.push_back(Pred);
4871 }
4872 };
4873
4874 AppendPredicate(StartVal, StartExtended);
4875 AppendPredicate(Accum, AccumExtended);
4876
4877 // *** Part3: Predicates are ready. Now go ahead and create the new addrec in
4878 // which the casts had been folded away. The caller can rewrite SymbolicPHI
4879 // into NewAR if it will also add the runtime overflow checks specified in
4880 // Predicates.
4881 auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap);
4882
4883 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite =
4884 std::make_pair(NewAR, Predicates);
4885 // Remember the result of the analysis for this SCEV at this locayyytion.
4886 PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite;
4887 return PredRewrite;
4888}
4889
4890Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
4891ScalarEvolution::createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI) {
4892 auto *PN = cast<PHINode>(SymbolicPHI->getValue());
4893 const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
4894 if (!L)
4895 return None;
4896
4897 // Check to see if we already analyzed this PHI.
4898 auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L});
4899 if (I != PredicatedSCEVRewrites.end()) {
4900 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite =
4901 I->second;
4902 // Analysis was done before and failed to create an AddRec:
4903 if (Rewrite.first == SymbolicPHI)
4904 return None;
4905 // Analysis was done before and succeeded to create an AddRec under
4906 // a predicate:
4907 assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec");
4908 assert(!(Rewrite.second).empty() && "Expected to find Predicates");
4909 return Rewrite;
4910 }
4911
4912 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
4913 Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI);
4914
4915 // Record in the cache that the analysis failed
4916 if (!Rewrite) {
4917 SmallVector<const SCEVPredicate *, 3> Predicates;
4918 PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates};
4919 return None;
4920 }
4921
4922 return Rewrite;
4923}
4924
4925// FIXME: This utility is currently required because the Rewriter currently
4926// does not rewrite this expression:
4927// {0, +, (sext ix (trunc iy to ix) to iy)}
4928// into {0, +, %step},
4929// even when the following Equal predicate exists:
4930// "%step == (sext ix (trunc iy to ix) to iy)".
4931bool PredicatedScalarEvolution::areAddRecsEqualWithPreds(
4932 const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2) const {
4933 if (AR1 == AR2)
4934 return true;
4935
4936 auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool {
4937 if (Expr1 != Expr2 && !Preds.implies(SE.getEqualPredicate(Expr1, Expr2)) &&
4938 !Preds.implies(SE.getEqualPredicate(Expr2, Expr1)))
4939 return false;
4940 return true;
4941 };
4942
4943 if (!areExprsEqual(AR1->getStart(), AR2->getStart()) ||
4944 !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE)))
4945 return false;
4946 return true;
4947}
4948
4949/// A helper function for createAddRecFromPHI to handle simple cases.
4950///
4951/// This function tries to find an AddRec expression for the simplest (yet most
4952/// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)).
4953/// If it fails, createAddRecFromPHI will use a more general, but slow,
4954/// technique for finding the AddRec expression.
4955const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN,
4956 Value *BEValueV,
4957 Value *StartValueV) {
4958 const Loop *L = LI.getLoopFor(PN->getParent());
4959 assert(L && L->getHeader() == PN->getParent());
4960 assert(BEValueV && StartValueV);
4961
4962 auto BO = MatchBinaryOp(BEValueV, DT);
4963 if (!BO)
4964 return nullptr;
4965
4966 if (BO->Opcode != Instruction::Add)
4967 return nullptr;
4968
4969 const SCEV *Accum = nullptr;
4970 if (BO->LHS == PN && L->isLoopInvariant(BO->RHS))
4971 Accum = getSCEV(BO->RHS);
4972 else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS))
4973 Accum = getSCEV(BO->LHS);
4974
4975 if (!Accum)
4976 return nullptr;
4977
4978 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
4979 if (BO->IsNUW)
4980 Flags = setFlags(Flags, SCEV::FlagNUW);
4981 if (BO->IsNSW)
4982 Flags = setFlags(Flags, SCEV::FlagNSW);
4983
4984 const SCEV *StartVal = getSCEV(StartValueV);
4985 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
4986
4987 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
4988
4989 // We can add Flags to the post-inc expression only if we
4990 // know that it is *undefined behavior* for BEValueV to
4991 // overflow.
4992 if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
4993 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
4994 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
4995
4996 return PHISCEV;
4997}
4998
4999const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) {
5000 const Loop *L = LI.getLoopFor(PN->getParent());
5001 if (!L || L->getHeader() != PN->getParent())
5002 return nullptr;
5003
5004 // The loop may have multiple entrances or multiple exits; we can analyze
5005 // this phi as an addrec if it has a unique entry value and a unique
5006 // backedge value.
5007 Value *BEValueV = nullptr, *StartValueV = nullptr;
5008 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5009 Value *V = PN->getIncomingValue(i);
5010 if (L->contains(PN->getIncomingBlock(i))) {
5011 if (!BEValueV) {
5012 BEValueV = V;
5013 } else if (BEValueV != V) {
5014 BEValueV = nullptr;
5015 break;
5016 }
5017 } else if (!StartValueV) {
5018 StartValueV = V;
5019 } else if (StartValueV != V) {
5020 StartValueV = nullptr;
5021 break;
5022 }
5023 }
5024 if (!BEValueV || !StartValueV)
5025 return nullptr;
5026
5027 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
5028 "PHI node already processed?");
5029
5030 // First, try to find AddRec expression without creating a fictituos symbolic
5031 // value for PN.
5032 if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV))
5033 return S;
5034
5035 // Handle PHI node value symbolically.
5036 const SCEV *SymbolicName = getUnknown(PN);
5037 ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName});
5038
5039 // Using this symbolic name for the PHI, analyze the value coming around
5040 // the back-edge.
5041 const SCEV *BEValue = getSCEV(BEValueV);
5042
5043 // NOTE: If BEValue is loop invariant, we know that the PHI node just
5044 // has a special value for the first iteration of the loop.
5045
5046 // If the value coming around the backedge is an add with the symbolic
5047 // value we just inserted, then we found a simple induction variable!
5048 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
5049 // If there is a single occurrence of the symbolic value, replace it
5050 // with a recurrence.
5051 unsigned FoundIndex = Add->getNumOperands();
5052 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5053 if (Add->getOperand(i) == SymbolicName)
5054 if (FoundIndex == e) {
5055 FoundIndex = i;
5056 break;
5057 }
5058
5059 if (FoundIndex != Add->getNumOperands()) {
5060 // Create an add with everything but the specified operand.
5061 SmallVector<const SCEV *, 8> Ops;
5062 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5063 if (i != FoundIndex)
5064 Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i),
5065 L, *this));
5066 const SCEV *Accum = getAddExpr(Ops);
5067
5068 // This is not a valid addrec if the step amount is varying each
5069 // loop iteration, but is not itself an addrec in this loop.
5070 if (isLoopInvariant(Accum, L) ||
5071 (isa<SCEVAddRecExpr>(Accum) &&
5072 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
5073 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5074
5075 if (auto BO = MatchBinaryOp(BEValueV, DT)) {
5076 if (BO->Opcode == Instruction::Add && BO->LHS == PN) {
5077 if (BO->IsNUW)
5078 Flags = setFlags(Flags, SCEV::FlagNUW);
5079 if (BO->IsNSW)
5080 Flags = setFlags(Flags, SCEV::FlagNSW);
5081 }
5082 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
5083 // If the increment is an inbounds GEP, then we know the address
5084 // space cannot be wrapped around. We cannot make any guarantee
5085 // about signed or unsigned overflow because pointers are
5086 // unsigned but we may have a negative index from the base
5087 // pointer. We can guarantee that no unsigned wrap occurs if the
5088 // indices form a positive value.
5089 if (GEP->isInBounds() && GEP->getOperand(0) == PN) {
5090 Flags = setFlags(Flags, SCEV::FlagNW);
5091
5092 const SCEV *Ptr = getSCEV(GEP->getPointerOperand());
5093 if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr)))
5094 Flags = setFlags(Flags, SCEV::FlagNUW);
5095 }
5096
5097 // We cannot transfer nuw and nsw flags from subtraction
5098 // operations -- sub nuw X, Y is not the same as add nuw X, -Y
5099 // for instance.
5100 }
5101
5102 const SCEV *StartVal = getSCEV(StartValueV);
5103 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
5104
5105 // Okay, for the entire analysis of this edge we assumed the PHI
5106 // to be symbolic. We now need to go back and purge all of the
5107 // entries for the scalars that use the symbolic expression.
5108 forgetSymbolicName(PN, SymbolicName);
5109 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
5110
5111 // We can add Flags to the post-inc expression only if we
5112 // know that it is *undefined behavior* for BEValueV to
5113 // overflow.
5114 if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
5115 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
5116 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5117
5118 return PHISCEV;
5119 }
5120 }
5121 } else {
5122 // Otherwise, this could be a loop like this:
5123 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
5124 // In this case, j = {1,+,1} and BEValue is j.
5125 // Because the other in-value of i (0) fits the evolution of BEValue
5126 // i really is an addrec evolution.
5127 //
5128 // We can generalize this saying that i is the shifted value of BEValue
5129 // by one iteration:
5130 // PHI(f(0), f({1,+,1})) --> f({0,+,1})
5131 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this);
5132 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false);
5133 if (Shifted != getCouldNotCompute() &&
5134 Start != getCouldNotCompute()) {
5135 const SCEV *StartVal = getSCEV(StartValueV);
5136 if (Start == StartVal) {
5137 // Okay, for the entire analysis of this edge we assumed the PHI
5138 // to be symbolic. We now need to go back and purge all of the
5139 // entries for the scalars that use the symbolic expression.
5140 forgetSymbolicName(PN, SymbolicName);
5141 ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted;
5142 return Shifted;
5143 }
5144 }
5145 }
5146
5147 // Remove the temporary PHI node SCEV that has been inserted while intending
5148 // to create an AddRecExpr for this PHI node. We can not keep this temporary
5149 // as it will prevent later (possibly simpler) SCEV expressions to be added
5150 // to the ValueExprMap.
5151 eraseValueFromMap(PN);
5152
5153 return nullptr;
5154}
5155
5156// Checks if the SCEV S is available at BB. S is considered available at BB
5157// if S can be materialized at BB without introducing a fault.
5158static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S,
5159 BasicBlock *BB) {
5160 struct CheckAvailable {
5161 bool TraversalDone = false;
5162 bool Available = true;
5163
5164 const Loop *L = nullptr; // The loop BB is in (can be nullptr)
5165 BasicBlock *BB = nullptr;
5166 DominatorTree &DT;
5167
5168 CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT)
5169 : L(L), BB(BB), DT(DT) {}
5170
5171 bool setUnavailable() {
5172 TraversalDone = true;
5173 Available = false;
5174 return false;
5175 }
5176
5177 bool follow(const SCEV *S) {
5178 switch (S->getSCEVType()) {
5179 case scConstant: case scTruncate: case scZeroExtend: case scSignExtend:
5180 case scAddExpr: case scMulExpr: case scUMaxExpr: case scSMaxExpr:
5181 case scUMinExpr:
5182 case scSMinExpr:
5183 // These expressions are available if their operand(s) is/are.
5184 return true;
5185
5186 case scAddRecExpr: {
5187 // We allow add recurrences that are on the loop BB is in, or some
5188 // outer loop. This guarantees availability because the value of the
5189 // add recurrence at BB is simply the "current" value of the induction
5190 // variable. We can relax this in the future; for instance an add
5191 // recurrence on a sibling dominating loop is also available at BB.
5192 const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop();
5193 if (L && (ARLoop == L || ARLoop->contains(L)))
5194 return true;
5195
5196 return setUnavailable();
5197 }
5198
5199 case scUnknown: {
5200 // For SCEVUnknown, we check for simple dominance.
5201 const auto *SU = cast<SCEVUnknown>(S);
5202 Value *V = SU->getValue();
5203
5204 if (isa<Argument>(V))
5205 return false;
5206
5207 if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB))
5208 return false;
5209
5210 return setUnavailable();
5211 }
5212
5213 case scUDivExpr:
5214 case scCouldNotCompute:
5215 // We do not try to smart about these at all.
5216 return setUnavailable();
5217 }
5218 llvm_unreachable("switch should be fully covered!");
5219 }
5220
5221 bool isDone() { return TraversalDone; }
5222 };
5223
5224 CheckAvailable CA(L, BB, DT);
5225 SCEVTraversal<CheckAvailable> ST(CA);
5226
5227 ST.visitAll(S);
5228 return CA.Available;
5229}
5230
5231// Try to match a control flow sequence that branches out at BI and merges back
5232// at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful
5233// match.
5234static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge,
5235 Value *&C, Value *&LHS, Value *&RHS) {
5236 C = BI->getCondition();
5237
5238 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0));
5239 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1));
5240
5241 if (!LeftEdge.isSingleEdge())
5242 return false;
5243
5244 assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()");
5245
5246 Use &LeftUse = Merge->getOperandUse(0);
5247 Use &RightUse = Merge->getOperandUse(1);
5248
5249 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) {
5250 LHS = LeftUse;
5251 RHS = RightUse;
5252 return true;
5253 }
5254
5255 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) {
5256 LHS = RightUse;
5257 RHS = LeftUse;
5258 return true;
5259 }
5260
5261 return false;
5262}
5263
5264const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) {
5265 auto IsReachable =
5266 [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); };
5267 if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) {
5268 const Loop *L = LI.getLoopFor(PN->getParent());
5269
5270 // We don't want to break LCSSA, even in a SCEV expression tree.
5271 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
5272 if (LI.getLoopFor(PN->getIncomingBlock(i)) != L)
5273 return nullptr;
5274
5275 // Try to match
5276 //
5277 // br %cond, label %left, label %right
5278 // left:
5279 // br label %merge
5280 // right:
5281 // br label %merge
5282 // merge:
5283 // V = phi [ %x, %left ], [ %y, %right ]
5284 //
5285 // as "select %cond, %x, %y"
5286
5287 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock();
5288 assert(IDom && "At least the entry block should dominate PN");
5289
5290 auto *BI = dyn_cast<BranchInst>(IDom->getTerminator());
5291 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
5292
5293 if (BI && BI->isConditional() &&
5294 BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) &&
5295 IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) &&
5296 IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent()))
5297 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS);
5298 }
5299
5300 return nullptr;
5301}
5302
5303const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
5304 if (const SCEV *S = createAddRecFromPHI(PN))
5305 return S;
5306
5307 if (const SCEV *S = createNodeFromSelectLikePHI(PN))
5308 return S;
5309
5310 // If the PHI has a single incoming value, follow that value, unless the
5311 // PHI's incoming blocks are in a different loop, in which case doing so
5312 // risks breaking LCSSA form. Instcombine would normally zap these, but
5313 // it doesn't have DominatorTree information, so it may miss cases.
5314 if (Value *V = SimplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC}))
5315 if (LI.replacementPreservesLCSSAForm(PN, V))
5316 return getSCEV(V);
5317
5318 // If it's not a loop phi, we can't handle it yet.
5319 return getUnknown(PN);
5320}
5321
5322const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I,
5323 Value *Cond,
5324 Value *TrueVal,
5325 Value *FalseVal) {
5326 // Handle "constant" branch or select. This can occur for instance when a
5327 // loop pass transforms an inner loop and moves on to process the outer loop.
5328 if (auto *CI = dyn_cast<ConstantInt>(Cond))
5329 return getSCEV(CI->isOne() ? TrueVal : FalseVal);
5330
5331 // Try to match some simple smax or umax patterns.
5332 auto *ICI = dyn_cast<ICmpInst>(Cond);
5333 if (!ICI)
5334 return getUnknown(I);
5335
5336 Value *LHS = ICI->getOperand(0);
5337 Value *RHS = ICI->getOperand(1);
5338
5339 switch (ICI->getPredicate()) {
5340 case ICmpInst::ICMP_SLT:
5341 case ICmpInst::ICMP_SLE:
5342 std::swap(LHS, RHS);
5343 LLVM_FALLTHROUGH;
5344 case ICmpInst::ICMP_SGT:
5345 case ICmpInst::ICMP_SGE:
5346 // a >s b ? a+x : b+x -> smax(a, b)+x
5347 // a >s b ? b+x : a+x -> smin(a, b)+x
5348 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
5349 const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType());
5350 const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType());
5351 const SCEV *LA = getSCEV(TrueVal);
5352 const SCEV *RA = getSCEV(FalseVal);
5353 const SCEV *LDiff = getMinusSCEV(LA, LS);
5354 const SCEV *RDiff = getMinusSCEV(RA, RS);
5355 if (LDiff == RDiff)
5356 return getAddExpr(getSMaxExpr(LS, RS), LDiff);
5357 LDiff = getMinusSCEV(LA, RS);
5358 RDiff = getMinusSCEV(RA, LS);
5359 if (LDiff == RDiff)
5360 return getAddExpr(getSMinExpr(LS, RS), LDiff);
5361 }
5362 break;
5363 case ICmpInst::ICMP_ULT:
5364 case ICmpInst::ICMP_ULE:
5365 std::swap(LHS, RHS);
5366 LLVM_FALLTHROUGH;
5367 case ICmpInst::ICMP_UGT:
5368 case ICmpInst::ICMP_UGE:
5369 // a >u b ? a+x : b+x -> umax(a, b)+x
5370 // a >u b ? b+x : a+x -> umin(a, b)+x
5371 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
5372 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5373 const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType());
5374 const SCEV *LA = getSCEV(TrueVal);
5375 const SCEV *RA = getSCEV(FalseVal);
5376 const SCEV *LDiff = getMinusSCEV(LA, LS);
5377 const SCEV *RDiff = getMinusSCEV(RA, RS);
5378 if (LDiff == RDiff)
5379 return getAddExpr(getUMaxExpr(LS, RS), LDiff);
5380 LDiff = getMinusSCEV(LA, RS);
5381 RDiff = getMinusSCEV(RA, LS);
5382 if (LDiff == RDiff)
5383 return getAddExpr(getUMinExpr(LS, RS), LDiff);
5384 }
5385 break;
5386 case ICmpInst::ICMP_NE:
5387 // n != 0 ? n+x : 1+x -> umax(n, 1)+x
5388 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
5389 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
5390 const SCEV *One = getOne(I->getType());
5391 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5392 const SCEV *LA = getSCEV(TrueVal);
5393 const SCEV *RA = getSCEV(FalseVal);
5394 const SCEV *LDiff = getMinusSCEV(LA, LS);
5395 const SCEV *RDiff = getMinusSCEV(RA, One);
5396 if (LDiff == RDiff)
5397 return getAddExpr(getUMaxExpr(One, LS), LDiff);
5398 }
5399 break;
5400 case ICmpInst::ICMP_EQ:
5401 // n == 0 ? 1+x : n+x -> umax(n, 1)+x
5402 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
5403 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
5404 const SCEV *One = getOne(I->getType());
5405 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5406 const SCEV *LA = getSCEV(TrueVal);
5407 const SCEV *RA = getSCEV(FalseVal);
5408 const SCEV *LDiff = getMinusSCEV(LA, One);
5409 const SCEV *RDiff = getMinusSCEV(RA, LS);
5410 if (LDiff == RDiff)
5411 return getAddExpr(getUMaxExpr(One, LS), LDiff);
5412 }
5413 break;
5414 default:
5415 break;
5416 }
5417
5418 return getUnknown(I);
5419}
5420
5421/// Expand GEP instructions into add and multiply operations. This allows them
5422/// to be analyzed by regular SCEV code.
5423const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
5424 // Don't attempt to analyze GEPs over unsized objects.
5425 if (!GEP->getSourceElementType()->isSized())
5426 return getUnknown(GEP);
5427 const DataLayout &DL = F.getParent()->getDataLayout();
5428 // FIXME: Ideally, we should teach Scalar Evolution to
5429 // understand fat pointers.
5430 if (DL.isFatPointer(GEP->getPointerOperandType()->getPointerAddressSpace()))
5431 return getUnknown(GEP);
5432
5433 SmallVector<const SCEV *, 4> IndexExprs;
5434 for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index)
5435 IndexExprs.push_back(getSCEV(*Index));
5436 return getGEPExpr(GEP, IndexExprs);
5437}
5438
5439uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) {
5440 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
5441 return C->getAPInt().countTrailingZeros();
5442
5443 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
5444 return std::min(GetMinTrailingZeros(T->getOperand()),
5445 (uint32_t)getTypeSizeInBits(T->getType()));
5446
5447 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
5448 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
5449 return OpRes == getTypeSizeInBits(E->getOperand()->getType())
5450 ? getTypeSizeInBits(E->getType())
5451 : OpRes;
5452 }
5453
5454 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
5455 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
5456 return OpRes == getTypeSizeInBits(E->getOperand()->getType())
5457 ? getTypeSizeInBits(E->getType())
5458 : OpRes;
5459 }
5460
5461 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
5462 // The result is the min of all operands results.
5463 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
5464 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
5465 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
5466 return MinOpRes;
5467 }
5468
5469 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
5470 // The result is the sum of all operands results.
5471 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
5472 unsigned BitWidth = getTypeSizeInBits(M->getType());
5473 for (unsigned i = 1, e = M->getNumOperands();
5474 SumOpRes != BitWidth && i != e; ++i)
5475 SumOpRes =
5476 std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth);
5477 return SumOpRes;
5478 }
5479
5480 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
5481 // The result is the min of all operands results.
5482 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
5483 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
5484 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
5485 return MinOpRes;
5486 }
5487
5488 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
5489 // The result is the min of all operands results.
5490 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
5491 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
5492 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
5493 return MinOpRes;
5494 }
5495
5496 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
5497 // The result is the min of all operands results.
5498 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
5499 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
5500 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
5501 return MinOpRes;
5502 }
5503
5504 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
5505 // For a SCEVUnknown, ask ValueTracking.
5506 KnownBits Known = computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT);
5507 return Known.countMinTrailingZeros();
5508 }
5509
5510 // SCEVUDivExpr
5511 return 0;
5512}
5513
5514uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
5515 auto I = MinTrailingZerosCache.find(S);
5516 if (I != MinTrailingZerosCache.end())
5517 return I->second;
5518
5519 uint32_t Result = GetMinTrailingZerosImpl(S);
5520 auto InsertPair = MinTrailingZerosCache.insert({S, Result});
5521 assert(InsertPair.second && "Should insert a new key");
5522 return InsertPair.first->second;
5523}
5524
5525/// Helper method to assign a range to V from metadata present in the IR.
5526static Optional<ConstantRange> GetRangeFromMetadata(Value *V) {
5527 if (Instruction *I = dyn_cast<Instruction>(V))
5528 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range))
5529 return getConstantRangeFromMetadata(*MD);
5530
5531 return None;
5532}
5533
5534/// Determine the range for a particular SCEV. If SignHint is
5535/// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges
5536/// with a "cleaner" unsigned (resp. signed) representation.
5537const ConstantRange &
5538ScalarEvolution::getRangeRef(const SCEV *S,
5539 ScalarEvolution::RangeSignHint SignHint) {
5540 DenseMap<const SCEV *, ConstantRange> &Cache =
5541 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
5542 : SignedRanges;
5543
5544 // See if we've computed this range already.
5545 DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S);
5546 if (I != Cache.end())
5547 return I->second;
5548
5549 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
5550 return setRange(C, SignHint, ConstantRange(C->getAPInt()));
5551
5552 unsigned BitWidth = getTypeSizeInBits(S->getType());
5553 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
5554
5555 // If the value has known zeros, the maximum value will have those known zeros
5556 // as well.
5557 uint32_t TZ = GetMinTrailingZeros(S);
5558 if (TZ != 0) {
5559 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED)
5560 ConservativeResult =
5561 ConstantRange(APInt::getMinValue(BitWidth),
5562 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
5563 else
5564 ConservativeResult = ConstantRange(
5565 APInt::getSignedMinValue(BitWidth),
5566 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
5567 }
5568
5569 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
5570 ConstantRange X = getRangeRef(Add->getOperand(0), SignHint);
5571 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
5572 X = X.add(getRangeRef(Add->getOperand(i), SignHint));
5573 return setRange(Add, SignHint, ConservativeResult.intersectWith(X));
5574 }
5575
5576 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
5577 ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint);
5578 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
5579 X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint));
5580 return setRange(Mul, SignHint, ConservativeResult.intersectWith(X));
5581 }
5582
5583 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
5584 ConstantRange X = getRangeRef(SMax->getOperand(0), SignHint);
5585 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
5586 X = X.smax(getRangeRef(SMax->getOperand(i), SignHint));
5587 return setRange(SMax, SignHint, ConservativeResult.intersectWith(X));
5588 }
5589
5590 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
5591 ConstantRange X = getRangeRef(UMax->getOperand(0), SignHint);
5592 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
5593 X = X.umax(getRangeRef(UMax->getOperand(i), SignHint));
5594 return setRange(UMax, SignHint, ConservativeResult.intersectWith(X));
5595 }
5596
5597 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
5598 ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint);
5599 ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint);
5600 return setRange(UDiv, SignHint,
5601 ConservativeResult.intersectWith(X.udiv(Y)));
5602 }
5603
5604 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
5605 ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint);
5606 return setRange(ZExt, SignHint,
5607 ConservativeResult.intersectWith(X.zeroExtend(BitWidth)));
5608 }
5609
5610 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
5611 ConstantRange X = getRangeRef(SExt->getOperand(), SignHint);
5612 return setRange(SExt, SignHint,
5613 ConservativeResult.intersectWith(X.signExtend(BitWidth)));
5614 }
5615
5616 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
5617 ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint);
5618 return setRange(Trunc, SignHint,
5619 ConservativeResult.intersectWith(X.truncate(BitWidth)));
5620 }
5621
5622 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
5623 // If there's no unsigned wrap, the value will never be less than its
5624 // initial value.
5625 if (AddRec->hasNoUnsignedWrap())
5626 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart()))
5627 if (!C->getValue()->isZero())
5628 ConservativeResult = ConservativeResult.intersectWith(
5629 ConstantRange(C->getAPInt(), APInt(BitWidth, 0)));
5630
5631 // If there's no signed wrap, and all the operands have the same sign or
5632 // zero, the value won't ever change sign.
5633 if (AddRec->hasNoSignedWrap()) {
5634 bool AllNonNeg = true;
5635 bool AllNonPos = true;
5636 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
5637 if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false;
5638 if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false;
5639 }
5640 if (AllNonNeg)
5641 ConservativeResult = ConservativeResult.intersectWith(
5642 ConstantRange(APInt(BitWidth, 0),
5643 APInt::getSignedMinValue(BitWidth)));
5644 else if (AllNonPos)
5645 ConservativeResult = ConservativeResult.intersectWith(
5646 ConstantRange(APInt::getSignedMinValue(BitWidth),
5647 APInt(BitWidth, 1)));
5648 }
5649
5650 // TODO: non-affine addrec
5651 if (AddRec->isAffine()) {
5652 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
5653 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
5654 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
5655 auto RangeFromAffine = getRangeForAffineAR(
5656 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
5657 BitWidth);
5658 if (!RangeFromAffine.isFullSet())
5659 ConservativeResult =
5660 ConservativeResult.intersectWith(RangeFromAffine);
5661
5662 auto RangeFromFactoring = getRangeViaFactoring(
5663 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
5664 BitWidth);
5665 if (!RangeFromFactoring.isFullSet())
5666 ConservativeResult =
5667 ConservativeResult.intersectWith(RangeFromFactoring);
5668 }
5669 }
5670
5671 return setRange(AddRec, SignHint, std::move(ConservativeResult));
5672 }
5673
5674 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
5675 // Check if the IR explicitly contains !range metadata.
5676 Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue());
5677 if (MDRange.hasValue())
5678 ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue());
5679
5680 // Split here to avoid paying the compile-time cost of calling both
5681 // computeKnownBits and ComputeNumSignBits. This restriction can be lifted
5682 // if needed.
5683 const DataLayout &DL = getDataLayout();
5684 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) {
5685 // For a SCEVUnknown, ask ValueTracking.
5686 KnownBits Known = computeKnownBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
5687 if (Known.One != ~Known.Zero + 1)
5688 ConservativeResult =
5689 ConservativeResult.intersectWith(ConstantRange(Known.One,
5690 ~Known.Zero + 1));
5691 } else {
5692 assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED &&
5693 "generalize as needed!");
5694 unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
5695 if (NS > 1)
5696 ConservativeResult = ConservativeResult.intersectWith(
5697 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
5698 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1));
5699 }
5700
5701 // A range of Phi is a subset of union of all ranges of its input.
5702 if (const PHINode *Phi = dyn_cast<PHINode>(U->getValue())) {
5703 // Make sure that we do not run over cycled Phis.
5704 if (PendingPhiRanges.insert(Phi).second) {
5705 ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false);
5706 for (auto &Op : Phi->operands()) {
5707 auto OpRange = getRangeRef(getSCEV(Op), SignHint);
5708 RangeFromOps = RangeFromOps.unionWith(OpRange);
5709 // No point to continue if we already have a full set.
5710 if (RangeFromOps.isFullSet())
5711 break;
5712 }
5713 ConservativeResult = ConservativeResult.intersectWith(RangeFromOps);
5714 bool Erased = PendingPhiRanges.erase(Phi);
5715 assert(Erased && "Failed to erase Phi properly?");
5716 (void) Erased;
5717 }
5718 }
5719
5720 return setRange(U, SignHint, std::move(ConservativeResult));
5721 }
5722
5723 return setRange(S, SignHint, std::move(ConservativeResult));
5724}
5725
5726// Given a StartRange, Step and MaxBECount for an expression compute a range of
5727// values that the expression can take. Initially, the expression has a value
5728// from StartRange and then is changed by Step up to MaxBECount times. Signed
5729// argument defines if we treat Step as signed or unsigned.
5730static ConstantRange getRangeForAffineARHelper(APInt Step,
5731 const ConstantRange &StartRange,
5732 const APInt &MaxBECount,
5733 unsigned BitWidth, bool Signed) {
5734 // If either Step or MaxBECount is 0, then the expression won't change, and we
5735 // just need to return the initial range.
5736 if (Step == 0 || MaxBECount == 0)
5737 return StartRange;
5738
5739 // If we don't know anything about the initial value (i.e. StartRange is
5740 // FullRange), then we don't know anything about the final range either.
5741 // Return FullRange.
5742 if (StartRange.isFullSet())
5743 return ConstantRange::getFull(BitWidth);
5744
5745 // If Step is signed and negative, then we use its absolute value, but we also
5746 // note that we're moving in the opposite direction.
5747 bool Descending = Signed && Step.isNegative();
5748
5749 if (Signed)
5750 // This is correct even for INT_SMIN. Let's look at i8 to illustrate this:
5751 // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128.
5752 // This equations hold true due to the well-defined wrap-around behavior of
5753 // APInt.
5754 Step = Step.abs();
5755
5756 // Check if Offset is more than full span of BitWidth. If it is, the
5757 // expression is guaranteed to overflow.
5758 if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount))
5759 return ConstantRange::getFull(BitWidth);
5760
5761 // Offset is by how much the expression can change. Checks above guarantee no
5762 // overflow here.
5763 APInt Offset = Step * MaxBECount;
5764
5765 // Minimum value of the final range will match the minimal value of StartRange
5766 // if the expression is increasing and will be decreased by Offset otherwise.
5767 // Maximum value of the final range will match the maximal value of StartRange
5768 // if the expression is decreasing and will be increased by Offset otherwise.
5769 APInt StartLower = StartRange.getLower();
5770 APInt StartUpper = StartRange.getUpper() - 1;
5771 APInt MovedBoundary = Descending ? (StartLower - std::move(Offset))
5772 : (StartUpper + std::move(Offset));
5773
5774 // It's possible that the new minimum/maximum value will fall into the initial
5775 // range (due to wrap around). This means that the expression can take any
5776 // value in this bitwidth, and we have to return full range.
5777 if (StartRange.contains(MovedBoundary))
5778 return ConstantRange::getFull(BitWidth);
5779
5780 APInt NewLower =
5781 Descending ? std::move(MovedBoundary) : std::move(StartLower);
5782 APInt NewUpper =
5783 Descending ? std::move(StartUpper) : std::move(MovedBoundary);
5784 NewUpper += 1;
5785
5786 // No overflow detected, return [StartLower, StartUpper + Offset + 1) range.
5787 return ConstantRange::getNonEmpty(std::move(NewLower), std::move(NewUpper));
5788}
5789
5790ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start,
5791 const SCEV *Step,
5792 const SCEV *MaxBECount,
5793 unsigned BitWidth) {
5794 assert(!isa<SCEVCouldNotCompute>(MaxBECount) &&
5795 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth &&
5796 "Precondition!");
5797
5798 MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType());
5799 APInt MaxBECountValue = getUnsignedRangeMax(MaxBECount);
5800
5801 // First, consider step signed.
5802 ConstantRange StartSRange = getSignedRange(Start);
5803 ConstantRange StepSRange = getSignedRange(Step);
5804
5805 // If Step can be both positive and negative, we need to find ranges for the
5806 // maximum absolute step values in both directions and union them.
5807 ConstantRange SR =
5808 getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange,
5809 MaxBECountValue, BitWidth, /* Signed = */ true);
5810 SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(),
5811 StartSRange, MaxBECountValue,
5812 BitWidth, /* Signed = */ true));
5813
5814 // Next, consider step unsigned.
5815 ConstantRange UR = getRangeForAffineARHelper(
5816 getUnsignedRangeMax(Step), getUnsignedRange(Start),
5817 MaxBECountValue, BitWidth, /* Signed = */ false);
5818
5819 // Finally, intersect signed and unsigned ranges.
5820 return SR.intersectWith(UR);
5821}
5822
5823ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start,
5824 const SCEV *Step,
5825 const SCEV *MaxBECount,
5826 unsigned BitWidth) {
5827 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q})
5828 // == RangeOf({A,+,P}) union RangeOf({B,+,Q})
5829
5830 struct SelectPattern {
5831 Value *Condition = nullptr;
5832 APInt TrueValue;
5833 APInt FalseValue;
5834
5835 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth,
5836 const SCEV *S) {
5837 Optional<unsigned> CastOp;
5838 APInt Offset(BitWidth, 0);
5839
5840 assert(SE.getTypeSizeInBits(S->getType()) == BitWidth &&
5841 "Should be!");
5842
5843 // Peel off a constant offset:
5844 if (auto *SA = dyn_cast<SCEVAddExpr>(S)) {
5845 // In the future we could consider being smarter here and handle
5846 // {Start+Step,+,Step} too.
5847 if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0)))
5848 return;
5849
5850 Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt();
5851 S = SA->getOperand(1);
5852 }
5853
5854 // Peel off a cast operation
5855 if (auto *SCast = dyn_cast<SCEVCastExpr>(S)) {
5856 CastOp = SCast->getSCEVType();
5857 S = SCast->getOperand();
5858 }
5859
5860 using namespace llvm::PatternMatch;
5861
5862 auto *SU = dyn_cast<SCEVUnknown>(S);
5863 const APInt *TrueVal, *FalseVal;
5864 if (!SU ||
5865 !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal),
5866 m_APInt(FalseVal)))) {
5867 Condition = nullptr;
5868 return;
5869 }
5870
5871 TrueValue = *TrueVal;
5872 FalseValue = *FalseVal;
5873
5874 // Re-apply the cast we peeled off earlier
5875 if (CastOp.hasValue())
5876 switch (*CastOp) {
5877 default:
5878 llvm_unreachable("Unknown SCEV cast type!");
5879
5880 case scTruncate:
5881 TrueValue = TrueValue.trunc(BitWidth);
5882 FalseValue = FalseValue.trunc(BitWidth);
5883 break;
5884 case scZeroExtend:
5885 TrueValue = TrueValue.zext(BitWidth);
5886 FalseValue = FalseValue.zext(BitWidth);
5887 break;
5888 case scSignExtend:
5889 TrueValue = TrueValue.sext(BitWidth);
5890 FalseValue = FalseValue.sext(BitWidth);
5891 break;
5892 }
5893
5894 // Re-apply the constant offset we peeled off earlier
5895 TrueValue += Offset;
5896 FalseValue += Offset;
5897 }
5898
5899 bool isRecognized() { return Condition != nullptr; }
5900 };
5901
5902 SelectPattern StartPattern(*this, BitWidth, Start);
5903 if (!StartPattern.isRecognized())
5904 return ConstantRange::getFull(BitWidth);
5905
5906 SelectPattern StepPattern(*this, BitWidth, Step);
5907 if (!StepPattern.isRecognized())
5908 return ConstantRange::getFull(BitWidth);
5909
5910 if (StartPattern.Condition != StepPattern.Condition) {
5911 // We don't handle this case today; but we could, by considering four
5912 // possibilities below instead of two. I'm not sure if there are cases where
5913 // that will help over what getRange already does, though.
5914 return ConstantRange::getFull(BitWidth);
5915 }
5916
5917 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to
5918 // construct arbitrary general SCEV expressions here. This function is called
5919 // from deep in the call stack, and calling getSCEV (on a sext instruction,
5920 // say) can end up caching a suboptimal value.
5921
5922 // FIXME: without the explicit `this` receiver below, MSVC errors out with
5923 // C2352 and C2512 (otherwise it isn't needed).
5924
5925 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue);
5926 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue);
5927 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue);
5928 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue);
5929
5930 ConstantRange TrueRange =
5931 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth);
5932 ConstantRange FalseRange =
5933 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth);
5934
5935 return TrueRange.unionWith(FalseRange);
5936}
5937
5938SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) {
5939 if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap;
5940 const BinaryOperator *BinOp = cast<BinaryOperator>(V);
5941
5942 // Return early if there are no flags to propagate to the SCEV.
5943 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5944 if (BinOp->hasNoUnsignedWrap())
5945 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
5946 if (BinOp->hasNoSignedWrap())
5947 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
5948 if (Flags == SCEV::FlagAnyWrap)
5949 return SCEV::FlagAnyWrap;
5950
5951 return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap;
5952}
5953
5954bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) {
5955 // Here we check that I is in the header of the innermost loop containing I,
5956 // since we only deal with instructions in the loop header. The actual loop we
5957 // need to check later will come from an add recurrence, but getting that
5958 // requires computing the SCEV of the operands, which can be expensive. This
5959 // check we can do cheaply to rule out some cases early.
5960 Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent());
5961 if (InnermostContainingLoop == nullptr ||
5962 InnermostContainingLoop->getHeader() != I->getParent())
5963 return false;
5964
5965 // Only proceed if we can prove that I does not yield poison.
5966 if (!programUndefinedIfFullPoison(I))
5967 return false;
5968
5969 // At this point we know that if I is executed, then it does not wrap
5970 // according to at least one of NSW or NUW. If I is not executed, then we do
5971 // not know if the calculation that I represents would wrap. Multiple
5972 // instructions can map to the same SCEV. If we apply NSW or NUW from I to
5973 // the SCEV, we must guarantee no wrapping for that SCEV also when it is
5974 // derived from other instructions that map to the same SCEV. We cannot make
5975 // that guarantee for cases where I is not executed. So we need to find the
5976 // loop that I is considered in relation to and prove that I is executed for
5977 // every iteration of that loop. That implies that the value that I
5978 // calculates does not wrap anywhere in the loop, so then we can apply the
5979 // flags to the SCEV.
5980 //
5981 // We check isLoopInvariant to disambiguate in case we are adding recurrences
5982 // from different loops, so that we know which loop to prove that I is
5983 // executed in.
5984 for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) {
5985 // I could be an extractvalue from a call to an overflow intrinsic.
5986 // TODO: We can do better here in some cases.
5987 if (!isSCEVable(I->getOperand(OpIndex)->getType()))
5988 return false;
5989 const SCEV *Op = getSCEV(I->getOperand(OpIndex));
5990 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
5991 bool AllOtherOpsLoopInvariant = true;
5992 for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands();
5993 ++OtherOpIndex) {
5994 if (OtherOpIndex != OpIndex) {
5995 const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex));
5996 if (!isLoopInvariant(OtherOp, AddRec->getLoop())) {
5997 AllOtherOpsLoopInvariant = false;
5998 break;
5999 }
6000 }
6001 }
6002 if (AllOtherOpsLoopInvariant &&
6003 isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop()))
6004 return true;
6005 }
6006 }
6007 return false;
6008}
6009
6010bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) {
6011 // If we know that \c I can never be poison period, then that's enough.
6012 if (isSCEVExprNeverPoison(I))
6013 return true;
6014
6015 // For an add recurrence specifically, we assume that infinite loops without
6016 // side effects are undefined behavior, and then reason as follows:
6017 //
6018 // If the add recurrence is poison in any iteration, it is poison on all
6019 // future iterations (since incrementing poison yields poison). If the result
6020 // of the add recurrence is fed into the loop latch condition and the loop
6021 // does not contain any throws or exiting blocks other than the latch, we now
6022 // have the ability to "choose" whether the backedge is taken or not (by
6023 // choosing a sufficiently evil value for the poison feeding into the branch)
6024 // for every iteration including and after the one in which \p I first became
6025 // poison. There are two possibilities (let's call the iteration in which \p
6026 // I first became poison as K):
6027 //
6028 // 1. In the set of iterations including and after K, the loop body executes
6029 // no side effects. In this case executing the backege an infinte number
6030 // of times will yield undefined behavior.
6031 //
6032 // 2. In the set of iterations including and after K, the loop body executes
6033 // at least one side effect. In this case, that specific instance of side
6034 // effect is control dependent on poison, which also yields undefined
6035 // behavior.
6036
6037 auto *ExitingBB = L->getExitingBlock();
6038 auto *LatchBB = L->getLoopLatch();
6039 if (!ExitingBB || !LatchBB || ExitingBB != LatchBB)
6040 return false;
6041
6042 SmallPtrSet<const Instruction *, 16> Pushed;
6043 SmallVector<const Instruction *, 8> PoisonStack;
6044
6045 // We start by assuming \c I, the post-inc add recurrence, is poison. Only
6046 // things that are known to be fully poison under that assumption go on the
6047 // PoisonStack.
6048 Pushed.insert(I);
6049 PoisonStack.push_back(I);
6050
6051 bool LatchControlDependentOnPoison = false;
6052 while (!PoisonStack.empty() && !LatchControlDependentOnPoison) {
6053 const Instruction *Poison = PoisonStack.pop_back_val();
6054
6055 for (auto *PoisonUser : Poison->users()) {
6056 if (propagatesFullPoison(cast<Instruction>(PoisonUser))) {
6057 if (Pushed.insert(cast<Instruction>(PoisonUser)).second)
6058 PoisonStack.push_back(cast<Instruction>(PoisonUser));
6059 } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) {
6060 assert(BI->isConditional() && "Only possibility!");
6061 if (BI->getParent() == LatchBB) {
6062 LatchControlDependentOnPoison = true;
6063 break;
6064 }
6065 }
6066 }
6067 }
6068
6069 return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L);
6070}
6071
6072ScalarEvolution::LoopProperties
6073ScalarEvolution::getLoopProperties(const Loop *L) {
6074 using LoopProperties = ScalarEvolution::LoopProperties;
6075
6076 auto Itr = LoopPropertiesCache.find(L);
6077 if (Itr == LoopPropertiesCache.end()) {
6078 auto HasSideEffects = [](Instruction *I) {
6079 if (auto *SI = dyn_cast<StoreInst>(I))
6080 return !SI->isSimple();
6081
6082 return I->mayHaveSideEffects();
6083 };
6084
6085 LoopProperties LP = {/* HasNoAbnormalExits */ true,
6086 /*HasNoSideEffects*/ true};
6087
6088 for (auto *BB : L->getBlocks())
6089 for (auto &I : *BB) {
6090 if (!isGuaranteedToTransferExecutionToSuccessor(&I))
6091 LP.HasNoAbnormalExits = false;
6092 if (HasSideEffects(&I))
6093 LP.HasNoSideEffects = false;
6094 if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects)
6095 break; // We're already as pessimistic as we can get.
6096 }
6097
6098 auto InsertPair = LoopPropertiesCache.insert({L, LP});
6099 assert(InsertPair.second && "We just checked!");
6100 Itr = InsertPair.first;
6101 }
6102
6103 return Itr->second;
6104}
6105
6106const SCEV *ScalarEvolution::createSCEV(Value *V) {
6107 if (!isSCEVable(V->getType()))
6108 return getUnknown(V);
6109
6110 if (Instruction *I = dyn_cast<Instruction>(V)) {
6111 // Don't attempt to analyze instructions in blocks that aren't
6112 // reachable. Such instructions don't matter, and they aren't required
6113 // to obey basic rules for definitions dominating uses which this
6114 // analysis depends on.
6115 if (!DT.isReachableFromEntry(I->getParent()))
6116 return getUnknown(UndefValue::get(V->getType()));
6117 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
6118 return getConstant(CI);
6119 else if (isa<ConstantPointerNull>(V))
6120 return getZero(V->getType());
6121 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
6122 return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee());
6123 else if (!isa<ConstantExpr>(V))
6124 return getUnknown(V);
6125
6126 Operator *U = cast<Operator>(V);
6127 if (auto BO = MatchBinaryOp(U, DT)) {
6128 switch (BO->Opcode) {
6129 case Instruction::Add: {
6130 // The simple thing to do would be to just call getSCEV on both operands
6131 // and call getAddExpr with the result. However if we're looking at a
6132 // bunch of things all added together, this can be quite inefficient,
6133 // because it leads to N-1 getAddExpr calls for N ultimate operands.
6134 // Instead, gather up all the operands and make a single getAddExpr call.
6135 // LLVM IR canonical form means we need only traverse the left operands.
6136 SmallVector<const SCEV *, 4> AddOps;
6137 do {
6138 if (BO->Op) {
6139 if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
6140 AddOps.push_back(OpSCEV);
6141 break;
6142 }
6143
6144 // If a NUW or NSW flag can be applied to the SCEV for this
6145 // addition, then compute the SCEV for this addition by itself
6146 // with a separate call to getAddExpr. We need to do that
6147 // instead of pushing the operands of the addition onto AddOps,
6148 // since the flags are only known to apply to this particular
6149 // addition - they may not apply to other additions that can be
6150 // formed with operands from AddOps.
6151 const SCEV *RHS = getSCEV(BO->RHS);
6152 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
6153 if (Flags != SCEV::FlagAnyWrap) {
6154 const SCEV *LHS = getSCEV(BO->LHS);
6155 if (BO->Opcode == Instruction::Sub)
6156 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags));
6157 else
6158 AddOps.push_back(getAddExpr(LHS, RHS, Flags));
6159 break;
6160 }
6161 }
6162
6163 if (BO->Opcode == Instruction::Sub)
6164 AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS)));
6165 else
6166 AddOps.push_back(getSCEV(BO->RHS));
6167
6168 auto NewBO = MatchBinaryOp(BO->LHS, DT);
6169 if (!NewBO || (NewBO->Opcode != Instruction::Add &&
6170 NewBO->Opcode != Instruction::Sub)) {
6171 AddOps.push_back(getSCEV(BO->LHS));
6172 break;
6173 }
6174 BO = NewBO;
6175 } while (true);
6176
6177 return getAddExpr(AddOps);
6178 }
6179
6180 case Instruction::Mul: {
6181 SmallVector<const SCEV *, 4> MulOps;
6182 do {
6183 if (BO->Op) {
6184 if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
6185 MulOps.push_back(OpSCEV);
6186 break;
6187 }
6188
6189 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
6190 if (Flags != SCEV::FlagAnyWrap) {
6191 MulOps.push_back(
6192 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags));
6193 break;
6194 }
6195 }
6196
6197 MulOps.push_back(getSCEV(BO->RHS));
6198 auto NewBO = MatchBinaryOp(BO->LHS, DT);
6199 if (!NewBO || NewBO->Opcode != Instruction::Mul) {
6200 MulOps.push_back(getSCEV(BO->LHS));
6201 break;
6202 }
6203 BO = NewBO;
6204 } while (true);
6205
6206 return getMulExpr(MulOps);
6207 }
6208 case Instruction::UDiv:
6209 return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
6210 case Instruction::URem:
6211 return getURemExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
6212 case Instruction::Sub: {
6213 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
6214 if (BO->Op)
6215 Flags = getNoWrapFlagsFromUB(BO->Op);
6216 return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags);
6217 }
6218 case Instruction::And:
6219 // For an expression like x&255 that merely masks off the high bits,
6220 // use zext(trunc(x)) as the SCEV expression.
6221 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
6222 if (CI->isZero())
6223 return getSCEV(BO->RHS);
6224 if (CI->isMinusOne())
6225 return getSCEV(BO->LHS);
6226 const APInt &A = CI->getValue();
6227
6228 // Instcombine's ShrinkDemandedConstant may strip bits out of
6229 // constants, obscuring what would otherwise be a low-bits mask.
6230 // Use computeKnownBits to compute what ShrinkDemandedConstant
6231 // knew about to reconstruct a low-bits mask value.
6232 unsigned LZ = A.countLeadingZeros();
6233 unsigned TZ = A.countTrailingZeros();
6234 unsigned BitWidth = A.getBitWidth();
6235 KnownBits Known(BitWidth);
6236 computeKnownBits(BO->LHS, Known, getDataLayout(),
6237 0, &AC, nullptr, &DT);
6238
6239 APInt EffectiveMask =
6240 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ);
6241 if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) {
6242 const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ));
6243 const SCEV *LHS = getSCEV(BO->LHS);
6244 const SCEV *ShiftedLHS = nullptr;
6245 if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) {
6246 if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) {
6247 // For an expression like (x * 8) & 8, simplify the multiply.
6248 unsigned MulZeros = OpC->getAPInt().countTrailingZeros();
6249 unsigned GCD = std::min(MulZeros, TZ);
6250 APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD);
6251 SmallVector<const SCEV*, 4> MulOps;
6252 MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD)));
6253 MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end());
6254 auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags());
6255 ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt));
6256 }
6257 }
6258 if (!ShiftedLHS)
6259 ShiftedLHS = getUDivExpr(LHS, MulCount);
6260 return getMulExpr(
6261 getZeroExtendExpr(
6262 getTruncateExpr(ShiftedLHS,
6263 IntegerType::get(getContext(), BitWidth - LZ - TZ)),
6264 BO->LHS->getType()),
6265 MulCount);
6266 }
6267 }
6268 break;
6269
6270 case Instruction::Or:
6271 // If the RHS of the Or is a constant, we may have something like:
6272 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
6273 // optimizations will transparently handle this case.
6274 //
6275 // In order for this transformation to be safe, the LHS must be of the
6276 // form X*(2^n) and the Or constant must be less than 2^n.
6277 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
6278 const SCEV *LHS = getSCEV(BO->LHS);
6279 const APInt &CIVal = CI->getValue();
6280 if (GetMinTrailingZeros(LHS) >=
6281 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
6282 // Build a plain add SCEV.
6283 const SCEV *S = getAddExpr(LHS, getSCEV(CI));
6284 // If the LHS of the add was an addrec and it has no-wrap flags,
6285 // transfer the no-wrap flags, since an or won't introduce a wrap.
6286 if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) {
6287 const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS);
6288 const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags(
6289 OldAR->getNoWrapFlags());
6290 }
6291 return S;
6292 }
6293 }
6294 break;
6295
6296 case Instruction::Xor:
6297 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
6298 // If the RHS of xor is -1, then this is a not operation.
6299 if (CI->isMinusOne())
6300 return getNotSCEV(getSCEV(BO->LHS));
6301
6302 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
6303 // This is a variant of the check for xor with -1, and it handles
6304 // the case where instcombine has trimmed non-demanded bits out
6305 // of an xor with -1.
6306 if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS))
6307 if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1)))
6308 if (LBO->getOpcode() == Instruction::And &&
6309 LCI->getValue() == CI->getValue())
6310 if (const SCEVZeroExtendExpr *Z =
6311 dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) {
6312 Type *UTy = BO->LHS->getType();
6313 const SCEV *Z0 = Z->getOperand();
6314 Type *Z0Ty = Z0->getType();
6315 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
6316
6317 // If C is a low-bits mask, the zero extend is serving to
6318 // mask off the high bits. Complement the operand and
6319 // re-apply the zext.
6320 if (CI->getValue().isMask(Z0TySize))
6321 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
6322
6323 // If C is a single bit, it may be in the sign-bit position
6324 // before the zero-extend. In this case, represent the xor
6325 // using an add, which is equivalent, and re-apply the zext.
6326 APInt Trunc = CI->getValue().trunc(Z0TySize);
6327 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
6328 Trunc.isSignMask())
6329 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
6330 UTy);
6331 }
6332 }
6333 break;
6334
6335 case Instruction::Shl:
6336 // Turn shift left of a constant amount into a multiply.
6337 if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) {
6338 uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth();
6339
6340 // If the shift count is not less than the bitwidth, the result of
6341 // the shift is undefined. Don't try to analyze it, because the
6342 // resolution chosen here may differ from the resolution chosen in
6343 // other parts of the compiler.
6344 if (SA->getValue().uge(BitWidth))
6345 break;
6346
6347 // It is currently not resolved how to interpret NSW for left
6348 // shift by BitWidth - 1, so we avoid applying flags in that
6349 // case. Remove this check (or this comment) once the situation
6350 // is resolved. See
6351 // http://lists.llvm.org/pipermail/llvm-dev/2015-April/084195.html
6352 // and http://reviews.llvm.org/D8890 .
6353 auto Flags = SCEV::FlagAnyWrap;
6354 if (BO->Op && SA->getValue().ult(BitWidth - 1))
6355 Flags = getNoWrapFlagsFromUB(BO->Op);
6356
6357 Constant *X = ConstantInt::get(
6358 getContext(), APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
6359 return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags);
6360 }
6361 break;
6362
6363 case Instruction::AShr: {
6364 // AShr X, C, where C is a constant.
6365 ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS);
6366 if (!CI)
6367 break;
6368
6369 Type *OuterTy = BO->LHS->getType();
6370 uint64_t BitWidth = getTypeSizeInBits(OuterTy);
6371 // If the shift count is not less than the bitwidth, the result of
6372 // the shift is undefined. Don't try to analyze it, because the
6373 // resolution chosen here may differ from the resolution chosen in
6374 // other parts of the compiler.
6375 if (CI->getValue().uge(BitWidth))
6376 break;
6377
6378 if (CI->isZero())
6379 return getSCEV(BO->LHS); // shift by zero --> noop
6380
6381 uint64_t AShrAmt = CI->getZExtValue();
6382 Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt);
6383
6384 Operator *L = dyn_cast<Operator>(BO->LHS);
6385 if (L && L->getOpcode() == Instruction::Shl) {
6386 // X = Shl A, n
6387 // Y = AShr X, m
6388 // Both n and m are constant.
6389
6390 const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0));
6391 if (L->getOperand(1) == BO->RHS)
6392 // For a two-shift sext-inreg, i.e. n = m,
6393 // use sext(trunc(x)) as the SCEV expression.
6394 return getSignExtendExpr(
6395 getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy);
6396
6397 ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1));
6398 if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) {
6399 uint64_t ShlAmt = ShlAmtCI->getZExtValue();
6400 if (ShlAmt > AShrAmt) {
6401 // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV
6402 // expression. We already checked that ShlAmt < BitWidth, so
6403 // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as
6404 // ShlAmt - AShrAmt < Amt.
6405 APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt,
6406 ShlAmt - AShrAmt);
6407 return getSignExtendExpr(
6408 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy),
6409 getConstant(Mul)), OuterTy);
6410 }
6411 }
6412 }
6413 break;
6414 }
6415 }
6416 }
6417
6418 switch (U->getOpcode()) {
6419 case Instruction::Trunc:
6420 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
6421
6422 case Instruction::ZExt:
6423 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
6424
6425 case Instruction::SExt:
6426 if (auto BO = MatchBinaryOp(U->getOperand(0), DT)) {
6427 // The NSW flag of a subtract does not always survive the conversion to
6428 // A + (-1)*B. By pushing sign extension onto its operands we are much
6429 // more likely to preserve NSW and allow later AddRec optimisations.
6430 //
6431 // NOTE: This is effectively duplicating this logic from getSignExtend:
6432 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
6433 // but by that point the NSW information has potentially been lost.
6434 if (BO->Opcode == Instruction::Sub && BO->IsNSW) {
6435 Type *Ty = U->getType();
6436 auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty);
6437 auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty);
6438 return getMinusSCEV(V1, V2, SCEV::FlagNSW);
6439 }
6440 }
6441 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
6442
6443 case Instruction::BitCast:
6444 // BitCasts are no-op casts so we just eliminate the cast.
6445 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
6446 return getSCEV(U->getOperand(0));
6447 break;
6448
6449 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can
6450 // lead to pointer expressions which cannot safely be expanded to GEPs,
6451 // because ScalarEvolution doesn't respect the GEP aliasing rules when
6452 // simplifying integer expressions.
6453
6454 case Instruction::GetElementPtr:
6455 return createNodeForGEP(cast<GEPOperator>(U));
6456
6457 case Instruction::PHI:
6458 return createNodeForPHI(cast<PHINode>(U));
6459
6460 case Instruction::Select:
6461 // U can also be a select constant expr, which let fall through. Since
6462 // createNodeForSelect only works for a condition that is an `ICmpInst`, and
6463 // constant expressions cannot have instructions as operands, we'd have
6464 // returned getUnknown for a select constant expressions anyway.
6465 if (isa<Instruction>(U))
6466 return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0),
6467 U->getOperand(1), U->getOperand(2));
6468 break;
6469
6470 case Instruction::Call:
6471 case Instruction::Invoke:
6472 if (Value *RV = CallSite(U).getReturnedArgOperand())
6473 return getSCEV(RV);
6474 break;
6475 }
6476
6477 return getUnknown(V);
6478}
6479
6480//===----------------------------------------------------------------------===//
6481// Iteration Count Computation Code
6482//
6483
6484static unsigned getConstantTripCount(const SCEVConstant *ExitCount) {
6485 if (!ExitCount)
6486 return 0;
6487
6488 ConstantInt *ExitConst = ExitCount->getValue();
6489
6490 // Guard against huge trip counts.
6491 if (ExitConst->getValue().getActiveBits() > 32)
6492 return 0;
6493
6494 // In case of integer overflow, this returns 0, which is correct.
6495 return ((unsigned)ExitConst->getZExtValue()) + 1;
6496}
6497
6498unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) {
6499 if (BasicBlock *ExitingBB = L->getExitingBlock())
6500 return getSmallConstantTripCount(L, ExitingBB);
6501
6502 // No trip count information for multiple exits.
6503 return 0;
6504}
6505
6506unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L,
6507 BasicBlock *ExitingBlock) {
6508 assert(ExitingBlock && "Must pass a non-null exiting block!");
6509 assert(L->isLoopExiting(ExitingBlock) &&
6510 "Exiting block must actually branch out of the loop!");
6511 const SCEVConstant *ExitCount =
6512 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock));
6513 return getConstantTripCount(ExitCount);
6514}
6515
6516unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) {
6517 const auto *MaxExitCount =
6518 dyn_cast<SCEVConstant>(getMaxBackedgeTakenCount(L));
6519 return getConstantTripCount(MaxExitCount);
6520}
6521
6522unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) {
6523 if (BasicBlock *ExitingBB = L->getExitingBlock())
6524 return getSmallConstantTripMultiple(L, ExitingBB);
6525
6526 // No trip multiple information for multiple exits.
6527 return 0;
6528}
6529
6530/// Returns the largest constant divisor of the trip count of this loop as a
6531/// normal unsigned value, if possible. This means that the actual trip count is
6532/// always a multiple of the returned value (don't forget the trip count could
6533/// very well be zero as well!).
6534///
6535/// Returns 1 if the trip count is unknown or not guaranteed to be the
6536/// multiple of a constant (which is also the case if the trip count is simply
6537/// constant, use getSmallConstantTripCount for that case), Will also return 1
6538/// if the trip count is very large (>= 2^32).
6539///
6540/// As explained in the comments for getSmallConstantTripCount, this assumes
6541/// that control exits the loop via ExitingBlock.
6542unsigned
6543ScalarEvolution::getSmallConstantTripMultiple(const Loop *L,
6544 BasicBlock *ExitingBlock) {
6545 assert(ExitingBlock && "Must pass a non-null exiting block!");
6546 assert(L->isLoopExiting(ExitingBlock) &&
6547 "Exiting block must actually branch out of the loop!");
6548 const SCEV *ExitCount = getExitCount(L, ExitingBlock);
6549 if (ExitCount == getCouldNotCompute())
6550 return 1;
6551
6552 // Get the trip count from the BE count by adding 1.
6553 const SCEV *TCExpr = getAddExpr(ExitCount, getOne(ExitCount->getType()));
6554
6555 const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr);
6556 if (!TC)
6557 // Attempt to factor more general cases. Returns the greatest power of
6558 // two divisor. If overflow happens, the trip count expression is still
6559 // divisible by the greatest power of 2 divisor returned.
6560 return 1U << std::min((uint32_t)31, GetMinTrailingZeros(TCExpr));
6561
6562 ConstantInt *Result = TC->getValue();
6563
6564 // Guard against huge trip counts (this requires checking
6565 // for zero to handle the case where the trip count == -1 and the
6566 // addition wraps).
6567 if (!Result || Result->getValue().getActiveBits() > 32 ||
6568 Result->getValue().getActiveBits() == 0)
6569 return 1;
6570
6571 return (unsigned)Result->getZExtValue();
6572}
6573
6574/// Get the expression for the number of loop iterations for which this loop is
6575/// guaranteed not to exit via ExitingBlock. Otherwise return
6576/// SCEVCouldNotCompute.
6577const SCEV *ScalarEvolution::getExitCount(const Loop *L,
6578 BasicBlock *ExitingBlock) {
6579 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
6580}
6581
6582const SCEV *
6583ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L,
6584 SCEVUnionPredicate &Preds) {
6585 return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds);
6586}
6587
6588const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
6589 return getBackedgeTakenInfo(L).getExact(L, this);
6590}
6591
6592/// Similar to getBackedgeTakenCount, except return the least SCEV value that is
6593/// known never to be less than the actual backedge taken count.
6594const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
6595 return getBackedgeTakenInfo(L).getMax(this);
6596}
6597
6598bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) {
6599 return getBackedgeTakenInfo(L).isMaxOrZero(this);
6600}
6601
6602/// Push PHI nodes in the header of the given loop onto the given Worklist.
6603static void
6604PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
6605 BasicBlock *Header = L->getHeader();
6606
6607 // Push all Loop-header PHIs onto the Worklist stack.
6608 for (PHINode &PN : Header->phis())
6609 Worklist.push_back(&PN);
6610}
6611
6612const ScalarEvolution::BackedgeTakenInfo &
6613ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) {
6614 auto &BTI = getBackedgeTakenInfo(L);
6615 if (BTI.hasFullInfo())
6616 return BTI;
6617
6618 auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
6619
6620 if (!Pair.second)
6621 return Pair.first->second;
6622
6623 BackedgeTakenInfo Result =
6624 computeBackedgeTakenCount(L, /*AllowPredicates=*/true);
6625
6626 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result);
6627}
6628
6629const ScalarEvolution::BackedgeTakenInfo &
6630ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
6631 // Initially insert an invalid entry for this loop. If the insertion
6632 // succeeds, proceed to actually compute a backedge-taken count and
6633 // update the value. The temporary CouldNotCompute value tells SCEV
6634 // code elsewhere that it shouldn't attempt to request a new
6635 // backedge-taken count, which could result in infinite recursion.
6636 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
6637 BackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
6638 if (!Pair.second)
6639 return Pair.first->second;
6640
6641 // computeBackedgeTakenCount may allocate memory for its result. Inserting it
6642 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
6643 // must be cleared in this scope.
6644 BackedgeTakenInfo Result = computeBackedgeTakenCount(L);
6645
6646 // In product build, there are no usage of statistic.
6647 (void)NumTripCountsComputed;
6648 (void)NumTripCountsNotComputed;
6649#if LLVM_ENABLE_STATS || !defined(NDEBUG)
6650 const SCEV *BEExact = Result.getExact(L, this);
6651 if (BEExact != getCouldNotCompute()) {
6652 assert(isLoopInvariant(BEExact, L) &&
6653 isLoopInvariant(Result.getMax(this), L) &&
6654 "Computed backedge-taken count isn't loop invariant for loop!");
6655 ++NumTripCountsComputed;
6656 }
6657 else if (Result.getMax(this) == getCouldNotCompute() &&
6658 isa<PHINode>(L->getHeader()->begin())) {
6659 // Only count loops that have phi nodes as not being computable.
6660 ++NumTripCountsNotComputed;
6661 }
6662#endif // LLVM_ENABLE_STATS || !defined(NDEBUG)
6663
6664 // Now that we know more about the trip count for this loop, forget any
6665 // existing SCEV values for PHI nodes in this loop since they are only
6666 // conservative estimates made without the benefit of trip count
6667 // information. This is similar to the code in forgetLoop, except that
6668 // it handles SCEVUnknown PHI nodes specially.
6669 if (Result.hasAnyInfo()) {
6670 SmallVector<Instruction *, 16> Worklist;
6671 PushLoopPHIs(L, Worklist);
6672
6673 SmallPtrSet<Instruction *, 8> Discovered;
6674 while (!Worklist.empty()) {
6675 Instruction *I = Worklist.pop_back_val();
6676
6677 ValueExprMapType::iterator It =
6678 ValueExprMap.find_as(static_cast<Value *>(I));
6679 if (It != ValueExprMap.end()) {
6680 const SCEV *Old = It->second;
6681
6682 // SCEVUnknown for a PHI either means that it has an unrecognized
6683 // structure, or it's a PHI that's in the progress of being computed
6684 // by createNodeForPHI. In the former case, additional loop trip
6685 // count information isn't going to change anything. In the later
6686 // case, createNodeForPHI will perform the necessary updates on its
6687 // own when it gets to that point.
6688 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) {
6689 eraseValueFromMap(It->first);
6690 forgetMemoizedResults(Old);
6691 }
6692 if (PHINode *PN = dyn_cast<PHINode>(I))
6693 ConstantEvolutionLoopExitValue.erase(PN);
6694 }
6695
6696 // Since we don't need to invalidate anything for correctness and we're
6697 // only invalidating to make SCEV's results more precise, we get to stop
6698 // early to avoid invalidating too much. This is especially important in
6699 // cases like:
6700 //
6701 // %v = f(pn0, pn1) // pn0 and pn1 used through some other phi node
6702 // loop0:
6703 // %pn0 = phi
6704 // ...
6705 // loop1:
6706 // %pn1 = phi
6707 // ...
6708 //
6709 // where both loop0 and loop1's backedge taken count uses the SCEV
6710 // expression for %v. If we don't have the early stop below then in cases
6711 // like the above, getBackedgeTakenInfo(loop1) will clear out the trip
6712 // count for loop0 and getBackedgeTakenInfo(loop0) will clear out the trip
6713 // count for loop1, effectively nullifying SCEV's trip count cache.
6714 for (auto *U : I->users())
6715 if (auto *I = dyn_cast<Instruction>(U)) {
6716 auto *LoopForUser = LI.getLoopFor(I->getParent());
6717 if (LoopForUser && L->contains(LoopForUser) &&
6718 Discovered.insert(I).second)
6719 Worklist.push_back(I);
6720 }
6721 }
6722 }
6723
6724 // Re-lookup the insert position, since the call to
6725 // computeBackedgeTakenCount above could result in a
6726 // recusive call to getBackedgeTakenInfo (on a different
6727 // loop), which would invalidate the iterator computed
6728 // earlier.
6729 return BackedgeTakenCounts.find(L)->second = std::move(Result);
6730}
6731
6732void ScalarEvolution::forgetAllLoops() {
6733 // This method is intended to forget all info about loops. It should
6734 // invalidate caches as if the following happened:
6735 // - The trip counts of all loops have changed arbitrarily
6736 // - Every llvm::Value has been updated in place to produce a different
6737 // result.
6738 BackedgeTakenCounts.clear();
6739 PredicatedBackedgeTakenCounts.clear();
6740 LoopPropertiesCache.clear();
6741 ConstantEvolutionLoopExitValue.clear();
6742 ValueExprMap.clear();
6743 ValuesAtScopes.clear();
6744 LoopDispositions.clear();
6745 BlockDispositions.clear();
6746 UnsignedRanges.clear();
6747 SignedRanges.clear();
6748 ExprValueMap.clear();
6749 HasRecMap.clear();
6750 MinTrailingZerosCache.clear();
6751 PredicatedSCEVRewrites.clear();
6752}
6753
6754void ScalarEvolution::forgetLoop(const Loop *L) {
6755 // Drop any stored trip count value.
6756 auto RemoveLoopFromBackedgeMap =
6757 [](DenseMap<const Loop *, BackedgeTakenInfo> &Map, const Loop *L) {
6758 auto BTCPos = Map.find(L);
6759 if (BTCPos != Map.end()) {
6760 BTCPos->second.clear();
6761 Map.erase(BTCPos);
6762 }
6763 };
6764
6765 SmallVector<const Loop *, 16> LoopWorklist(1, L);
6766 SmallVector<Instruction *, 32> Worklist;
6767 SmallPtrSet<Instruction *, 16> Visited;
6768
6769 // Iterate over all the loops and sub-loops to drop SCEV information.
6770 while (!LoopWorklist.empty()) {
6771 auto *CurrL = LoopWorklist.pop_back_val();
6772
6773 RemoveLoopFromBackedgeMap(BackedgeTakenCounts, CurrL);
6774 RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts, CurrL);
6775
6776 // Drop information about predicated SCEV rewrites for this loop.
6777 for (auto I = PredicatedSCEVRewrites.begin();
6778 I != PredicatedSCEVRewrites.end();) {
6779 std::pair<const SCEV *, const Loop *> Entry = I->first;
6780 if (Entry.second == CurrL)
6781 PredicatedSCEVRewrites.erase(I++);
6782 else
6783 ++I;
6784 }
6785
6786 auto LoopUsersItr = LoopUsers.find(CurrL);
6787 if (LoopUsersItr != LoopUsers.end()) {
6788 for (auto *S : LoopUsersItr->second)
6789 forgetMemoizedResults(S);
6790 LoopUsers.erase(LoopUsersItr);
6791 }
6792
6793 // Drop information about expressions based on loop-header PHIs.
6794 PushLoopPHIs(CurrL, Worklist);
6795
6796 while (!Worklist.empty()) {
6797 Instruction *I = Worklist.pop_back_val();
6798 if (!Visited.insert(I).second)
6799 continue;
6800
6801 ValueExprMapType::iterator It =
6802 ValueExprMap.find_as(static_cast<Value *>(I));
6803 if (It != ValueExprMap.end()) {
6804 eraseValueFromMap(It->first);
6805 forgetMemoizedResults(It->second);
6806 if (PHINode *PN = dyn_cast<PHINode>(I))
6807 ConstantEvolutionLoopExitValue.erase(PN);
6808 }
6809
6810 PushDefUseChildren(I, Worklist);
6811 }
6812
6813 LoopPropertiesCache.erase(CurrL);
6814 // Forget all contained loops too, to avoid dangling entries in the
6815 // ValuesAtScopes map.
6816 LoopWorklist.append(CurrL->begin(), CurrL->end());
6817 }
6818}
6819
6820void ScalarEvolution::forgetTopmostLoop(const Loop *L) {
6821 while (Loop *Parent = L->getParentLoop())
6822 L = Parent;
6823 forgetLoop(L);
6824}
6825
6826void ScalarEvolution::forgetValue(Value *V) {
6827 Instruction *I = dyn_cast<Instruction>(V);
6828 if (!I) return;
6829
6830 // Drop information about expressions based on loop-header PHIs.
6831 SmallVector<Instruction *, 16> Worklist;
6832 Worklist.push_back(I);
6833
6834 SmallPtrSet<Instruction *, 8> Visited;
6835 while (!Worklist.empty()) {
6836 I = Worklist.pop_back_val();
6837 if (!Visited.insert(I).second)
6838 continue;
6839
6840 ValueExprMapType::iterator It =
6841 ValueExprMap.find_as(static_cast<Value *>(I));
6842 if (It != ValueExprMap.end()) {
6843 eraseValueFromMap(It->first);
6844 forgetMemoizedResults(It->second);
6845 if (PHINode *PN = dyn_cast<PHINode>(I))
6846 ConstantEvolutionLoopExitValue.erase(PN);
6847 }
6848
6849 PushDefUseChildren(I, Worklist);
6850 }
6851}
6852
6853/// Get the exact loop backedge taken count considering all loop exits. A
6854/// computable result can only be returned for loops with all exiting blocks
6855/// dominating the latch. howFarToZero assumes that the limit of each loop test
6856/// is never skipped. This is a valid assumption as long as the loop exits via
6857/// that test. For precise results, it is the caller's responsibility to specify
6858/// the relevant loop exiting block using getExact(ExitingBlock, SE).
6859const SCEV *
6860ScalarEvolution::BackedgeTakenInfo::getExact(const Loop *L, ScalarEvolution *SE,
6861 SCEVUnionPredicate *Preds) const {
6862 // If any exits were not computable, the loop is not computable.
6863 if (!isComplete() || ExitNotTaken.empty())
6864 return SE->getCouldNotCompute();
6865
6866 const BasicBlock *Latch = L->getLoopLatch();
6867 // All exiting blocks we have collected must dominate the only backedge.
6868 if (!Latch)
6869 return SE->getCouldNotCompute();
6870
6871 // All exiting blocks we have gathered dominate loop's latch, so exact trip
6872 // count is simply a minimum out of all these calculated exit counts.
6873 SmallVector<const SCEV *, 2> Ops;
6874 for (auto &ENT : ExitNotTaken) {
6875 const SCEV *BECount = ENT.ExactNotTaken;
6876 assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!");
6877 assert(SE->DT.dominates(ENT.ExitingBlock, Latch) &&
6878 "We should only have known counts for exiting blocks that dominate "
6879 "latch!");
6880
6881 Ops.push_back(BECount);
6882
6883 if (Preds && !ENT.hasAlwaysTruePredicate())
6884 Preds->add(ENT.Predicate.get());
6885
6886 assert((Preds || ENT.hasAlwaysTruePredicate()) &&
6887 "Predicate should be always true!");
6888 }
6889
6890 return SE->getUMinFromMismatchedTypes(Ops);
6891}
6892
6893/// Get the exact not taken count for this loop exit.
6894const SCEV *
6895ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock,
6896 ScalarEvolution *SE) const {
6897 for (auto &ENT : ExitNotTaken)
6898 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
6899 return ENT.ExactNotTaken;
6900
6901 return SE->getCouldNotCompute();
6902}
6903
6904/// getMax - Get the max backedge taken count for the loop.
6905const SCEV *
6906ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const {
6907 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
6908 return !ENT.hasAlwaysTruePredicate();
6909 };
6910
6911 if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getMax())
6912 return SE->getCouldNotCompute();
6913
6914 assert((isa<SCEVCouldNotCompute>(getMax()) || isa<SCEVConstant>(getMax())) &&
6915 "No point in having a non-constant max backedge taken count!");
6916 return getMax();
6917}
6918
6919bool ScalarEvolution::BackedgeTakenInfo::isMaxOrZero(ScalarEvolution *SE) const {
6920 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
6921 return !ENT.hasAlwaysTruePredicate();
6922 };
6923 return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue);
6924}
6925
6926bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S,
6927 ScalarEvolution *SE) const {
6928 if (getMax() && getMax() != SE->getCouldNotCompute() &&
6929 SE->hasOperand(getMax(), S))
6930 return true;
6931
6932 for (auto &ENT : ExitNotTaken)
6933 if (ENT.ExactNotTaken != SE->getCouldNotCompute() &&
6934 SE->hasOperand(ENT.ExactNotTaken, S))
6935 return true;
6936
6937 return false;
6938}
6939
6940ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E)
6941 : ExactNotTaken(E), MaxNotTaken(E) {
6942 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
6943 isa<SCEVConstant>(MaxNotTaken)) &&
6944 "No point in having a non-constant max backedge taken count!");
6945}
6946
6947ScalarEvolution::ExitLimit::ExitLimit(
6948 const SCEV *E, const SCEV *M, bool MaxOrZero,
6949 ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList)
6950 : ExactNotTaken(E), MaxNotTaken(M), MaxOrZero(MaxOrZero) {
6951 assert((isa<SCEVCouldNotCompute>(ExactNotTaken) ||
6952 !isa<SCEVCouldNotCompute>(MaxNotTaken)) &&
6953 "Exact is not allowed to be less precise than Max");
6954 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
6955 isa<SCEVConstant>(MaxNotTaken)) &&
6956 "No point in having a non-constant max backedge taken count!");
6957 for (auto *PredSet : PredSetList)
6958 for (auto *P : *PredSet)
6959 addPredicate(P);
6960}
6961
6962ScalarEvolution::ExitLimit::ExitLimit(
6963 const SCEV *E, const SCEV *M, bool MaxOrZero,
6964 const SmallPtrSetImpl<const SCEVPredicate *> &PredSet)
6965 : ExitLimit(E, M, MaxOrZero, {&PredSet}) {
6966 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
6967 isa<SCEVConstant>(MaxNotTaken)) &&
6968 "No point in having a non-constant max backedge taken count!");
6969}
6970
6971ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E, const SCEV *M,
6972 bool MaxOrZero)
6973 : ExitLimit(E, M, MaxOrZero, None) {
6974 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
6975 isa<SCEVConstant>(MaxNotTaken)) &&
6976 "No point in having a non-constant max backedge taken count!");
6977}
6978
6979/// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
6980/// computable exit into a persistent ExitNotTakenInfo array.
6981ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
6982 ArrayRef<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo>
6983 ExitCounts,
6984 bool Complete, const SCEV *MaxCount, bool MaxOrZero)
6985 : MaxAndComplete(MaxCount, Complete), MaxOrZero(MaxOrZero) {
6986 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
6987
6988 ExitNotTaken.reserve(ExitCounts.size());
6989 std::transform(
6990 ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken),
6991 [&](const EdgeExitInfo &EEI) {
6992 BasicBlock *ExitBB = EEI.first;
6993 const ExitLimit &EL = EEI.second;
6994 if (EL.Predicates.empty())
6995 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, nullptr);
6996
6997 std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate);
6998 for (auto *Pred : EL.Predicates)
6999 Predicate->add(Pred);
7000
7001 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, std::move(Predicate));
7002 });
7003 assert((isa<SCEVCouldNotCompute>(MaxCount) || isa<SCEVConstant>(MaxCount)) &&
7004 "No point in having a non-constant max backedge taken count!");
7005}
7006
7007/// Invalidate this result and free the ExitNotTakenInfo array.
7008void ScalarEvolution::BackedgeTakenInfo::clear() {
7009 ExitNotTaken.clear();
7010}
7011
7012/// Compute the number of times the backedge of the specified loop will execute.
7013ScalarEvolution::BackedgeTakenInfo
7014ScalarEvolution::computeBackedgeTakenCount(const Loop *L,
7015 bool AllowPredicates) {
7016 SmallVector<BasicBlock *, 8> ExitingBlocks;
7017 L->getExitingBlocks(ExitingBlocks);
7018
7019 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
7020
7021 SmallVector<EdgeExitInfo, 4> ExitCounts;
7022 bool CouldComputeBECount = true;
7023 BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
7024 const SCEV *MustExitMaxBECount = nullptr;
7025 const SCEV *MayExitMaxBECount = nullptr;
7026 bool MustExitMaxOrZero = false;
7027
7028 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
7029 // and compute maxBECount.
7030 // Do a union of all the predicates here.
7031 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
7032 BasicBlock *ExitBB = ExitingBlocks[i];
7033 ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates);
7034
7035 assert((AllowPredicates || EL.Predicates.empty()) &&
7036 "Predicated exit limit when predicates are not allowed!");
7037
7038 // 1. For each exit that can be computed, add an entry to ExitCounts.
7039 // CouldComputeBECount is true only if all exits can be computed.
7040 if (EL.ExactNotTaken == getCouldNotCompute())
7041 // We couldn't compute an exact value for this exit, so
7042 // we won't be able to compute an exact value for the loop.
7043 CouldComputeBECount = false;
7044 else
7045 ExitCounts.emplace_back(ExitBB, EL);
7046
7047 // 2. Derive the loop's MaxBECount from each exit's max number of
7048 // non-exiting iterations. Partition the loop exits into two kinds:
7049 // LoopMustExits and LoopMayExits.
7050 //
7051 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it
7052 // is a LoopMayExit. If any computable LoopMustExit is found, then
7053 // MaxBECount is the minimum EL.MaxNotTaken of computable
7054 // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum
7055 // EL.MaxNotTaken, where CouldNotCompute is considered greater than any
7056 // computable EL.MaxNotTaken.
7057 if (EL.MaxNotTaken != getCouldNotCompute() && Latch &&
7058 DT.dominates(ExitBB, Latch)) {
7059 if (!MustExitMaxBECount) {
7060 MustExitMaxBECount = EL.MaxNotTaken;
7061 MustExitMaxOrZero = EL.MaxOrZero;
7062 } else {
7063 MustExitMaxBECount =
7064 getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken);
7065 }
7066 } else if (MayExitMaxBECount != getCouldNotCompute()) {
7067 if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute())
7068 MayExitMaxBECount = EL.MaxNotTaken;
7069 else {
7070 MayExitMaxBECount =
7071 getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken);
7072 }
7073 }
7074 }
7075 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
7076 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
7077 // The loop backedge will be taken the maximum or zero times if there's
7078 // a single exit that must be taken the maximum or zero times.
7079 bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1);
7080 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount,
7081 MaxBECount, MaxOrZero);
7082}
7083
7084ScalarEvolution::ExitLimit
7085ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock,
7086 bool AllowPredicates) {
7087 assert(L->contains(ExitingBlock) && "Exit count for non-loop block?");
7088 // If our exiting block does not dominate the latch, then its connection with
7089 // loop's exit limit may be far from trivial.
7090 const BasicBlock *Latch = L->getLoopLatch();
7091 if (!Latch || !DT.dominates(ExitingBlock, Latch))
7092 return getCouldNotCompute();
7093
7094 bool IsOnlyExit = (L->getExitingBlock() != nullptr);
7095 Instruction *Term = ExitingBlock->getTerminator();
7096 if (BranchInst *BI = dyn_cast<BranchInst>(Term)) {
7097 assert(BI->isConditional() && "If unconditional, it can't be in loop!");
7098 bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
7099 assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) &&
7100 "It should have one successor in loop and one exit block!");
7101 // Proceed to the next level to examine the exit condition expression.
7102 return computeExitLimitFromCond(
7103 L, BI->getCondition(), ExitIfTrue,
7104 /*ControlsExit=*/IsOnlyExit, AllowPredicates);
7105 }
7106
7107 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) {
7108 // For switch, make sure that there is a single exit from the loop.
7109 BasicBlock *Exit = nullptr;
7110 for (auto *SBB : successors(ExitingBlock))
7111 if (!L->contains(SBB)) {
7112 if (Exit) // Multiple exit successors.
7113 return getCouldNotCompute();
7114 Exit = SBB;
7115 }
7116 assert(Exit && "Exiting block must have at least one exit");
7117 return computeExitLimitFromSingleExitSwitch(L, SI, Exit,
7118 /*ControlsExit=*/IsOnlyExit);
7119 }
7120
7121 return getCouldNotCompute();
7122}
7123
7124ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond(
7125 const Loop *L, Value *ExitCond, bool ExitIfTrue,
7126 bool ControlsExit, bool AllowPredicates) {
7127 ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates);
7128 return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue,
7129 ControlsExit, AllowPredicates);
7130}
7131
7132Optional<ScalarEvolution::ExitLimit>
7133ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond,
7134 bool ExitIfTrue, bool ControlsExit,
7135 bool AllowPredicates) {
7136 (void)this->L;
7137 (void)this->ExitIfTrue;
7138 (void)this->AllowPredicates;
7139
7140 assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
7141 this->AllowPredicates == AllowPredicates &&
7142 "Variance in assumed invariant key components!");
7143 auto Itr = TripCountMap.find({ExitCond, ControlsExit});
7144 if (Itr == TripCountMap.end())
7145 return None;
7146 return Itr->second;
7147}
7148
7149void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond,
7150 bool ExitIfTrue,
7151 bool ControlsExit,
7152 bool AllowPredicates,
7153 const ExitLimit &EL) {
7154 assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
7155 this->AllowPredicates == AllowPredicates &&
7156 "Variance in assumed invariant key components!");
7157
7158 auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL});
7159 assert(InsertResult.second && "Expected successful insertion!");
7160 (void)InsertResult;
7161 (void)ExitIfTrue;
7162}
7163
7164ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached(
7165 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
7166 bool ControlsExit, bool AllowPredicates) {
7167
7168 if (auto MaybeEL =
7169 Cache.find(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates))
7170 return *MaybeEL;
7171
7172 ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, ExitIfTrue,
7173 ControlsExit, AllowPredicates);
7174 Cache.insert(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates, EL);
7175 return EL;
7176}
7177
7178ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl(
7179 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
7180 bool ControlsExit, bool AllowPredicates) {
7181 // Check if the controlling expression for this loop is an And or Or.
7182 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
7183 if (BO->getOpcode() == Instruction::And) {
7184 // Recurse on the operands of the and.
7185 bool EitherMayExit = !ExitIfTrue;
7186 ExitLimit EL0 = computeExitLimitFromCondCached(
7187 Cache, L, BO->getOperand(0), ExitIfTrue,
7188 ControlsExit && !EitherMayExit, AllowPredicates);
7189 ExitLimit EL1 = computeExitLimitFromCondCached(
7190 Cache, L, BO->getOperand(1), ExitIfTrue,
7191 ControlsExit && !EitherMayExit, AllowPredicates);
7192 const SCEV *BECount = getCouldNotCompute();
7193 const SCEV *MaxBECount = getCouldNotCompute();
7194 if (EitherMayExit) {
7195 // Both conditions must be true for the loop to continue executing.
7196 // Choose the less conservative count.
7197 if (EL0.ExactNotTaken == getCouldNotCompute() ||
7198 EL1.ExactNotTaken == getCouldNotCompute())
7199 BECount = getCouldNotCompute();
7200 else
7201 BECount =
7202 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken);
7203 if (EL0.MaxNotTaken == getCouldNotCompute())
7204 MaxBECount = EL1.MaxNotTaken;
7205 else if (EL1.MaxNotTaken == getCouldNotCompute())
7206 MaxBECount = EL0.MaxNotTaken;
7207 else
7208 MaxBECount =
7209 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
7210 } else {
7211 // Both conditions must be true at the same time for the loop to exit.
7212 // For now, be conservative.
7213 if (EL0.MaxNotTaken == EL1.MaxNotTaken)
7214 MaxBECount = EL0.MaxNotTaken;
7215 if (EL0.ExactNotTaken == EL1.ExactNotTaken)
7216 BECount = EL0.ExactNotTaken;
7217 }
7218
7219 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able
7220 // to be more aggressive when computing BECount than when computing
7221 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and
7222 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken
7223 // to not.
7224 if (isa<SCEVCouldNotCompute>(MaxBECount) &&
7225 !isa<SCEVCouldNotCompute>(BECount))
7226 MaxBECount = getConstant(getUnsignedRangeMax(BECount));
7227
7228 return ExitLimit(BECount, MaxBECount, false,
7229 {&EL0.Predicates, &EL1.Predicates});
7230 }
7231 if (BO->getOpcode() == Instruction::Or) {
7232 // Recurse on the operands of the or.
7233 bool EitherMayExit = ExitIfTrue;
7234 ExitLimit EL0 = computeExitLimitFromCondCached(
7235 Cache, L, BO->getOperand(0), ExitIfTrue,
7236 ControlsExit && !EitherMayExit, AllowPredicates);
7237 ExitLimit EL1 = computeExitLimitFromCondCached(
7238 Cache, L, BO->getOperand(1), ExitIfTrue,
7239 ControlsExit && !EitherMayExit, AllowPredicates);
7240 const SCEV *BECount = getCouldNotCompute();
7241 const SCEV *MaxBECount = getCouldNotCompute();
7242 if (EitherMayExit) {
7243 // Both conditions must be false for the loop to continue executing.
7244 // Choose the less conservative count.
7245 if (EL0.ExactNotTaken == getCouldNotCompute() ||
7246 EL1.ExactNotTaken == getCouldNotCompute())
7247 BECount = getCouldNotCompute();
7248 else
7249 BECount =
7250 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken);
7251 if (EL0.MaxNotTaken == getCouldNotCompute())
7252 MaxBECount = EL1.MaxNotTaken;
7253 else if (EL1.MaxNotTaken == getCouldNotCompute())
7254 MaxBECount = EL0.MaxNotTaken;
7255 else
7256 MaxBECount =
7257 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
7258 } else {
7259 // Both conditions must be false at the same time for the loop to exit.
7260 // For now, be conservative.
7261 if (EL0.MaxNotTaken == EL1.MaxNotTaken)
7262 MaxBECount = EL0.MaxNotTaken;
7263 if (EL0.ExactNotTaken == EL1.ExactNotTaken)
7264 BECount = EL0.ExactNotTaken;
7265 }
7266 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able
7267 // to be more aggressive when computing BECount than when computing
7268 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and
7269 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken
7270 // to not.
7271 if (isa<SCEVCouldNotCompute>(MaxBECount) &&
7272 !isa<SCEVCouldNotCompute>(BECount))
7273 MaxBECount = getConstant(getUnsignedRangeMax(BECount));
7274
7275 return ExitLimit(BECount, MaxBECount, false,
7276 {&EL0.Predicates, &EL1.Predicates});
7277 }
7278 }
7279
7280 // With an icmp, it may be feasible to compute an exact backedge-taken count.
7281 // Proceed to the next level to examine the icmp.
7282 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) {
7283 ExitLimit EL =
7284 computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit);
7285 if (EL.hasFullInfo() || !AllowPredicates)
7286 return EL;
7287
7288 // Try again, but use SCEV predicates this time.
7289 return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit,
7290 /*AllowPredicates=*/true);
7291 }
7292
7293 // Check for a constant condition. These are normally stripped out by
7294 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
7295 // preserve the CFG and is temporarily leaving constant conditions
7296 // in place.
7297 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
7298 if (ExitIfTrue == !CI->getZExtValue())
7299 // The backedge is always taken.
7300 return getCouldNotCompute();
7301 else
7302 // The backedge is never taken.
7303 return getZero(CI->getType());
7304 }
7305
7306 // If it's not an integer or pointer comparison then compute it the hard way.
7307 return computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
7308}
7309
7310ScalarEvolution::ExitLimit
7311ScalarEvolution::computeExitLimitFromICmp(const Loop *L,
7312 ICmpInst *ExitCond,
7313 bool ExitIfTrue,
7314 bool ControlsExit,
7315 bool AllowPredicates) {
7316 // If the condition was exit on true, convert the condition to exit on false
7317 ICmpInst::Predicate Pred;
7318 if (!ExitIfTrue)
7319 Pred = ExitCond->getPredicate();
7320 else
7321 Pred = ExitCond->getInversePredicate();
7322 const ICmpInst::Predicate OriginalPred = Pred;
7323
7324 // Handle common loops like: for (X = "string"; *X; ++X)
7325 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
7326 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
7327 ExitLimit ItCnt =
7328 computeLoadConstantCompareExitLimit(LI, RHS, L, Pred);
7329 if (ItCnt.hasAnyInfo())
7330 return ItCnt;
7331 }
7332
7333 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
7334 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
7335
7336 // Try to evaluate any dependencies out of the loop.
7337 LHS = getSCEVAtScope(LHS, L);
7338 RHS = getSCEVAtScope(RHS, L);
7339
7340 // At this point, we would like to compute how many iterations of the
7341 // loop the predicate will return true for these inputs.
7342 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
7343 // If there is a loop-invariant, force it into the RHS.
7344 std::swap(LHS, RHS);
7345 Pred = ICmpInst::getSwappedPredicate(Pred);
7346 }
7347
7348 // Simplify the operands before analyzing them.
7349 (void)SimplifyICmpOperands(Pred, LHS, RHS);
7350
7351 // If we have a comparison of a chrec against a constant, try to use value
7352 // ranges to answer this query.
7353 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
7354 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
7355 if (AddRec->getLoop() == L) {
7356 // Form the constant range.
7357 ConstantRange CompRange =
7358 ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt());
7359
7360 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
7361 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
7362 }
7363
7364 switch (Pred) {
7365 case ICmpInst::ICMP_NE: { // while (X != Y)
7366 // Convert to: while (X-Y != 0)
7367 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit,
7368 AllowPredicates);
7369 if (EL.hasAnyInfo()) return EL;
7370 break;
7371 }
7372 case ICmpInst::ICMP_EQ: { // while (X == Y)
7373 // Convert to: while (X-Y == 0)
7374 ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L);
7375 if (EL.hasAnyInfo()) return EL;
7376 break;
7377 }
7378 case ICmpInst::ICMP_SLT:
7379 case ICmpInst::ICMP_ULT: { // while (X < Y)
7380 bool IsSigned = Pred == ICmpInst::ICMP_SLT;
7381 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit,
7382 AllowPredicates);
7383 if (EL.hasAnyInfo()) return EL;
7384 break;
7385 }
7386 case ICmpInst::ICMP_SGT:
7387 case ICmpInst::ICMP_UGT: { // while (X > Y)
7388 bool IsSigned = Pred == ICmpInst::ICMP_SGT;
7389 ExitLimit EL =
7390 howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit,
7391 AllowPredicates);
7392 if (EL.hasAnyInfo()) return EL;
7393 break;
7394 }
7395 default:
7396 break;
7397 }
7398
7399 auto *ExhaustiveCount =
7400 computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
7401
7402 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount))
7403 return ExhaustiveCount;
7404
7405 return computeShiftCompareExitLimit(ExitCond->getOperand(0),
7406 ExitCond->getOperand(1), L, OriginalPred);
7407}
7408
7409ScalarEvolution::ExitLimit
7410ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L,
7411 SwitchInst *Switch,
7412 BasicBlock *ExitingBlock,
7413 bool ControlsExit) {
7414 assert(!L->contains(ExitingBlock) && "Not an exiting block!");
7415
7416 // Give up if the exit is the default dest of a switch.
7417 if (Switch->getDefaultDest() == ExitingBlock)
7418 return getCouldNotCompute();
7419
7420 assert(L->contains(Switch->getDefaultDest()) &&
7421 "Default case must not exit the loop!");
7422 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L);
7423 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock));
7424
7425 // while (X != Y) --> while (X-Y != 0)
7426 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit);
7427 if (EL.hasAnyInfo())
7428 return EL;
7429
7430 return getCouldNotCompute();
7431}
7432
7433static ConstantInt *
7434EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
7435 ScalarEvolution &SE) {
7436 const SCEV *InVal = SE.getConstant(C);
7437 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
7438 assert(isa<SCEVConstant>(Val) &&
7439 "Evaluation of SCEV at constant didn't fold correctly?");
7440 return cast<SCEVConstant>(Val)->getValue();
7441}
7442
7443/// Given an exit condition of 'icmp op load X, cst', try to see if we can
7444/// compute the backedge execution count.
7445ScalarEvolution::ExitLimit
7446ScalarEvolution::computeLoadConstantCompareExitLimit(
7447 LoadInst *LI,
7448 Constant *RHS,
7449 const Loop *L,
7450 ICmpInst::Predicate predicate) {
7451 if (LI->isVolatile()) return getCouldNotCompute();
7452
7453 // Check to see if the loaded pointer is a getelementptr of a global.
7454 // TODO: Use SCEV instead of manually grubbing with GEPs.
7455 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
7456 if (!GEP) return getCouldNotCompute();
7457
7458 // Make sure that it is really a constant global we are gepping, with an
7459 // initializer, and make sure the first IDX is really 0.
7460 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
7461 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
7462 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
7463 !cast<Constant>(GEP->getOperand(1))->isNullValue())
7464 return getCouldNotCompute();
7465
7466 // Okay, we allow one non-constant index into the GEP instruction.
7467 Value *VarIdx = nullptr;
7468 std::vector<Constant*> Indexes;
7469 unsigned VarIdxNum = 0;
7470 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
7471 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
7472 Indexes.push_back(CI);
7473 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
7474 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's.
7475 VarIdx = GEP->getOperand(i);
7476 VarIdxNum = i-2;
7477 Indexes.push_back(nullptr);
7478 }
7479
7480 // Loop-invariant loads may be a byproduct of loop optimization. Skip them.
7481 if (!VarIdx)
7482 return getCouldNotCompute();
7483
7484 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
7485 // Check to see if X is a loop variant variable value now.
7486 const SCEV *Idx = getSCEV(VarIdx);
7487 Idx = getSCEVAtScope(Idx, L);
7488
7489 // We can only recognize very limited forms of loop index expressions, in
7490 // particular, only affine AddRec's like {C1,+,C2}.
7491 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
7492 if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) ||
7493 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
7494 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
7495 return getCouldNotCompute();
7496
7497 unsigned MaxSteps = MaxBruteForceIterations;
7498 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
7499 ConstantInt *ItCst = ConstantInt::get(
7500 cast<IntegerType>(IdxExpr->getType()), IterationNum);
7501 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
7502
7503 // Form the GEP offset.
7504 Indexes[VarIdxNum] = Val;
7505
7506 Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(),
7507 Indexes);
7508 if (!Result) break; // Cannot compute!
7509
7510 // Evaluate the condition for this iteration.
7511 Result = ConstantExpr::getICmp(predicate, Result, RHS);
7512 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
7513 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
7514 ++NumArrayLenItCounts;
7515 return getConstant(ItCst); // Found terminating iteration!
7516 }
7517 }
7518 return getCouldNotCompute();
7519}
7520
7521ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit(
7522 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) {
7523 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV);
7524 if (!RHS)
7525 return getCouldNotCompute();
7526
7527 const BasicBlock *Latch = L->getLoopLatch();
7528 if (!Latch)
7529 return getCouldNotCompute();
7530
7531 const BasicBlock *Predecessor = L->getLoopPredecessor();
7532 if (!Predecessor)
7533 return getCouldNotCompute();
7534
7535 // Return true if V is of the form "LHS `shift_op` <positive constant>".
7536 // Return LHS in OutLHS and shift_opt in OutOpCode.
7537 auto MatchPositiveShift =
7538 [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) {
7539
7540 using namespace PatternMatch;
7541
7542 ConstantInt *ShiftAmt;
7543 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
7544 OutOpCode = Instruction::LShr;
7545 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
7546 OutOpCode = Instruction::AShr;
7547 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
7548 OutOpCode = Instruction::Shl;
7549 else
7550 return false;
7551
7552 return ShiftAmt->getValue().isStrictlyPositive();
7553 };
7554
7555 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in
7556 //
7557 // loop:
7558 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ]
7559 // %iv.shifted = lshr i32 %iv, <positive constant>
7560 //
7561 // Return true on a successful match. Return the corresponding PHI node (%iv
7562 // above) in PNOut and the opcode of the shift operation in OpCodeOut.
7563 auto MatchShiftRecurrence =
7564 [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) {
7565 Optional<Instruction::BinaryOps> PostShiftOpCode;
7566
7567 {
7568 Instruction::BinaryOps OpC;
7569 Value *V;
7570
7571 // If we encounter a shift instruction, "peel off" the shift operation,
7572 // and remember that we did so. Later when we inspect %iv's backedge
7573 // value, we will make sure that the backedge value uses the same
7574 // operation.
7575 //
7576 // Note: the peeled shift operation does not have to be the same
7577 // instruction as the one feeding into the PHI's backedge value. We only
7578 // really care about it being the same *kind* of shift instruction --
7579 // that's all that is required for our later inferences to hold.
7580 if (MatchPositiveShift(LHS, V, OpC)) {
7581 PostShiftOpCode = OpC;
7582 LHS = V;
7583 }
7584 }
7585
7586 PNOut = dyn_cast<PHINode>(LHS);
7587 if (!PNOut || PNOut->getParent() != L->getHeader())
7588 return false;
7589
7590 Value *BEValue = PNOut->getIncomingValueForBlock(Latch);
7591 Value *OpLHS;
7592
7593 return
7594 // The backedge value for the PHI node must be a shift by a positive
7595 // amount
7596 MatchPositiveShift(BEValue, OpLHS, OpCodeOut) &&
7597
7598 // of the PHI node itself
7599 OpLHS == PNOut &&
7600
7601 // and the kind of shift should be match the kind of shift we peeled
7602 // off, if any.
7603 (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut);
7604 };
7605
7606 PHINode *PN;
7607 Instruction::BinaryOps OpCode;
7608 if (!MatchShiftRecurrence(LHS, PN, OpCode))
7609 return getCouldNotCompute();
7610
7611 const DataLayout &DL = getDataLayout();
7612
7613 // The key rationale for this optimization is that for some kinds of shift
7614 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1
7615 // within a finite number of iterations. If the condition guarding the
7616 // backedge (in the sense that the backedge is taken if the condition is true)
7617 // is false for the value the shift recurrence stabilizes to, then we know
7618 // that the backedge is taken only a finite number of times.
7619
7620 ConstantInt *StableValue = nullptr;
7621 switch (OpCode) {
7622 default:
7623 llvm_unreachable("Impossible case!");
7624
7625 case Instruction::AShr: {
7626 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most
7627 // bitwidth(K) iterations.
7628 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor);
7629 KnownBits Known = computeKnownBits(FirstValue, DL, 0, nullptr,
7630 Predecessor->getTerminator(), &DT);
7631 auto *Ty = cast<IntegerType>(RHS->getType());
7632 if (Known.isNonNegative())
7633 StableValue = ConstantInt::get(Ty, 0);
7634 else if (Known.isNegative())
7635 StableValue = ConstantInt::get(Ty, -1, true);
7636 else
7637 return getCouldNotCompute();
7638
7639 break;
7640 }
7641 case Instruction::LShr:
7642 case Instruction::Shl:
7643 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>}
7644 // stabilize to 0 in at most bitwidth(K) iterations.
7645 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0);
7646 break;
7647 }
7648
7649 auto *Result =
7650 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI);
7651 assert(Result->getType()->isIntegerTy(1) &&
7652 "Otherwise cannot be an operand to a branch instruction");
7653
7654 if (Result->isZeroValue()) {
7655 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
7656 const SCEV *UpperBound =
7657 getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth);
7658 return ExitLimit(getCouldNotCompute(), UpperBound, false);
7659 }
7660
7661 return getCouldNotCompute();
7662}
7663
7664/// Return true if we can constant fold an instruction of the specified type,
7665/// assuming that all operands were constants.
7666static bool CanConstantFold(const Instruction *I) {
7667 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
7668 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
7669 isa<LoadInst>(I))
7670 return true;
7671
7672 if (const CallInst *CI = dyn_cast<CallInst>(I))
7673 if (const Function *F = CI->getCalledFunction())
7674 return canConstantFoldCallTo(CI, F);
7675 return false;
7676}
7677
7678/// Determine whether this instruction can constant evolve within this loop
7679/// assuming its operands can all constant evolve.
7680static bool canConstantEvolve(Instruction *I, const Loop *L) {
7681 // An instruction outside of the loop can't be derived from a loop PHI.
7682 if (!L->contains(I)) return false;
7683
7684 if (isa<PHINode>(I)) {
7685 // We don't currently keep track of the control flow needed to evaluate
7686 // PHIs, so we cannot handle PHIs inside of loops.
7687 return L->getHeader() == I->getParent();
7688 }
7689
7690 // If we won't be able to constant fold this expression even if the operands
7691 // are constants, bail early.
7692 return CanConstantFold(I);
7693}
7694
7695/// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
7696/// recursing through each instruction operand until reaching a loop header phi.
7697static PHINode *
7698getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L,
7699 DenseMap<Instruction *, PHINode *> &PHIMap,
7700 unsigned Depth) {
7701 if (Depth > MaxConstantEvolvingDepth)
7702 return nullptr;
7703
7704 // Otherwise, we can evaluate this instruction if all of its operands are
7705 // constant or derived from a PHI node themselves.
7706 PHINode *PHI = nullptr;
7707 for (Value *Op : UseInst->operands()) {
7708 if (isa<Constant>(Op)) continue;
7709
7710 Instruction *OpInst = dyn_cast<Instruction>(Op);
7711 if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr;
7712
7713 PHINode *P = dyn_cast<PHINode>(OpInst);
7714 if (!P)
7715 // If this operand is already visited, reuse the prior result.
7716 // We may have P != PHI if this is the deepest point at which the
7717 // inconsistent paths meet.
7718 P = PHIMap.lookup(OpInst);
7719 if (!P) {
7720 // Recurse and memoize the results, whether a phi is found or not.
7721 // This recursive call invalidates pointers into PHIMap.
7722 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1);
7723 PHIMap[OpInst] = P;
7724 }
7725 if (!P)
7726 return nullptr; // Not evolving from PHI
7727 if (PHI && PHI != P)
7728 return nullptr; // Evolving from multiple different PHIs.
7729 PHI = P;
7730 }
7731 // This is a expression evolving from a constant PHI!
7732 return PHI;
7733}
7734
7735/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
7736/// in the loop that V is derived from. We allow arbitrary operations along the
7737/// way, but the operands of an operation must either be constants or a value
7738/// derived from a constant PHI. If this expression does not fit with these
7739/// constraints, return null.
7740static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
7741 Instruction *I = dyn_cast<Instruction>(V);
7742 if (!I || !canConstantEvolve(I, L)) return nullptr;
7743
7744 if (PHINode *PN = dyn_cast<PHINode>(I))
7745 return PN;
7746
7747 // Record non-constant instructions contained by the loop.
7748 DenseMap<Instruction *, PHINode *> PHIMap;
7749 return getConstantEvolvingPHIOperands(I, L, PHIMap, 0);
7750}
7751
7752/// EvaluateExpression - Given an expression that passes the
7753/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
7754/// in the loop has the value PHIVal. If we can't fold this expression for some
7755/// reason, return null.
7756static Constant *EvaluateExpression(Value *V, const Loop *L,
7757 DenseMap<Instruction *, Constant *> &Vals,
7758 const DataLayout &DL,
7759 const TargetLibraryInfo *TLI) {
7760 // Convenient constant check, but redundant for recursive calls.
7761 if (Constant *C = dyn_cast<Constant>(V)) return C;
7762 Instruction *I = dyn_cast<Instruction>(V);
7763 if (!I) return nullptr;
7764
7765 if (Constant *C = Vals.lookup(I)) return C;
7766
7767 // An instruction inside the loop depends on a value outside the loop that we
7768 // weren't given a mapping for, or a value such as a call inside the loop.
7769 if (!canConstantEvolve(I, L)) return nullptr;
7770
7771 // An unmapped PHI can be due to a branch or another loop inside this loop,
7772 // or due to this not being the initial iteration through a loop where we
7773 // couldn't compute the evolution of this particular PHI last time.
7774 if (isa<PHINode>(I)) return nullptr;
7775
7776 std::vector<Constant*> Operands(I->getNumOperands());
7777
7778 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
7779 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i));
7780 if (!Operand) {
7781 Operands[i] = dyn_cast<Constant>(I->getOperand(i));
7782 if (!Operands[i]) return nullptr;
7783 continue;
7784 }
7785 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI);
7786 Vals[Operand] = C;
7787 if (!C) return nullptr;
7788 Operands[i] = C;
7789 }
7790
7791 if (CmpInst *CI = dyn_cast<CmpInst>(I))
7792 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
7793 Operands[1], DL, TLI);
7794 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
7795 if (!LI->isVolatile())
7796 return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
7797 }
7798 return ConstantFoldInstOperands(I, Operands, DL, TLI);
7799}
7800
7801
7802// If every incoming value to PN except the one for BB is a specific Constant,
7803// return that, else return nullptr.
7804static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) {
7805 Constant *IncomingVal = nullptr;
7806
7807 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
7808 if (PN->getIncomingBlock(i) == BB)
7809 continue;
7810
7811 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i));
7812 if (!CurrentVal)
7813 return nullptr;
7814
7815 if (IncomingVal != CurrentVal) {
7816 if (IncomingVal)
7817 return nullptr;
7818 IncomingVal = CurrentVal;
7819 }
7820 }
7821
7822 return IncomingVal;
7823}
7824
7825/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
7826/// in the header of its containing loop, we know the loop executes a
7827/// constant number of times, and the PHI node is just a recurrence
7828/// involving constants, fold it.
7829Constant *
7830ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
7831 const APInt &BEs,
7832 const Loop *L) {
7833 auto I = ConstantEvolutionLoopExitValue.find(PN);
7834 if (I != ConstantEvolutionLoopExitValue.end())
7835 return I->second;
7836
7837 if (BEs.ugt(MaxBruteForceIterations))
7838 return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it.
7839
7840 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
7841
7842 DenseMap<Instruction *, Constant *> CurrentIterVals;
7843 BasicBlock *Header = L->getHeader();
7844 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
7845
7846 BasicBlock *Latch = L->getLoopLatch();
7847 if (!Latch)
7848 return nullptr;
7849
7850 for (PHINode &PHI : Header->phis()) {
7851 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
7852 CurrentIterVals[&PHI] = StartCST;
7853 }
7854 if (!CurrentIterVals.count(PN))
7855 return RetVal = nullptr;
7856
7857 Value *BEValue = PN->getIncomingValueForBlock(Latch);
7858
7859 // Execute the loop symbolically to determine the exit value.
7860 assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) &&
7861 "BEs is <= MaxBruteForceIterations which is an 'unsigned'!");
7862
7863 unsigned NumIterations = BEs.getZExtValue(); // must be in range
7864 unsigned IterationNum = 0;
7865 const DataLayout &DL = getDataLayout();
7866 for (; ; ++IterationNum) {
7867 if (IterationNum == NumIterations)
7868 return RetVal = CurrentIterVals[PN]; // Got exit value!
7869
7870 // Compute the value of the PHIs for the next iteration.
7871 // EvaluateExpression adds non-phi values to the CurrentIterVals map.
7872 DenseMap<Instruction *, Constant *> NextIterVals;
7873 Constant *NextPHI =
7874 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
7875 if (!NextPHI)
7876 return nullptr; // Couldn't evaluate!
7877 NextIterVals[PN] = NextPHI;
7878
7879 bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
7880
7881 // Also evaluate the other PHI nodes. However, we don't get to stop if we
7882 // cease to be able to evaluate one of them or if they stop evolving,
7883 // because that doesn't necessarily prevent us from computing PN.
7884 SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute;
7885 for (const auto &I : CurrentIterVals) {
7886 PHINode *PHI = dyn_cast<PHINode>(I.first);
7887 if (!PHI || PHI == PN || PHI->getParent() != Header) continue;
7888 PHIsToCompute.emplace_back(PHI, I.second);
7889 }
7890 // We use two distinct loops because EvaluateExpression may invalidate any
7891 // iterators into CurrentIterVals.
7892 for (const auto &I : PHIsToCompute) {
7893 PHINode *PHI = I.first;
7894 Constant *&NextPHI = NextIterVals[PHI];
7895 if (!NextPHI) { // Not already computed.
7896 Value *BEValue = PHI->getIncomingValueForBlock(Latch);
7897 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
7898 }
7899 if (NextPHI != I.second)
7900 StoppedEvolving = false;
7901 }
7902
7903 // If all entries in CurrentIterVals == NextIterVals then we can stop
7904 // iterating, the loop can't continue to change.
7905 if (StoppedEvolving)
7906 return RetVal = CurrentIterVals[PN];
7907
7908 CurrentIterVals.swap(NextIterVals);
7909 }
7910}
7911
7912const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L,
7913 Value *Cond,
7914 bool ExitWhen) {
7915 PHINode *PN = getConstantEvolvingPHI(Cond, L);
7916 if (!PN) return getCouldNotCompute();
7917
7918 // If the loop is canonicalized, the PHI will have exactly two entries.
7919 // That's the only form we support here.
7920 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
7921
7922 DenseMap<Instruction *, Constant *> CurrentIterVals;
7923 BasicBlock *Header = L->getHeader();
7924 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
7925
7926 BasicBlock *Latch = L->getLoopLatch();
7927 assert(Latch && "Should follow from NumIncomingValues == 2!");
7928
7929 for (PHINode &PHI : Header->phis()) {
7930 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
7931 CurrentIterVals[&PHI] = StartCST;
7932 }
7933 if (!CurrentIterVals.count(PN))
7934 return getCouldNotCompute();
7935
7936 // Okay, we find a PHI node that defines the trip count of this loop. Execute
7937 // the loop symbolically to determine when the condition gets a value of
7938 // "ExitWhen".
7939 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
7940 const DataLayout &DL = getDataLayout();
7941 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
7942 auto *CondVal = dyn_cast_or_null<ConstantInt>(
7943 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI));
7944
7945 // Couldn't symbolically evaluate.
7946 if (!CondVal) return getCouldNotCompute();
7947
7948 if (CondVal->getValue() == uint64_t(ExitWhen)) {
7949 ++NumBruteForceTripCountsComputed;
7950 return getConstant(Type::getInt32Ty(getContext()), IterationNum);
7951 }
7952
7953 // Update all the PHI nodes for the next iteration.
7954 DenseMap<Instruction *, Constant *> NextIterVals;
7955
7956 // Create a list of which PHIs we need to compute. We want to do this before
7957 // calling EvaluateExpression on them because that may invalidate iterators
7958 // into CurrentIterVals.
7959 SmallVector<PHINode *, 8> PHIsToCompute;
7960 for (const auto &I : CurrentIterVals) {
7961 PHINode *PHI = dyn_cast<PHINode>(I.first);
7962 if (!PHI || PHI->getParent() != Header) continue;
7963 PHIsToCompute.push_back(PHI);
7964 }
7965 for (PHINode *PHI : PHIsToCompute) {
7966 Constant *&NextPHI = NextIterVals[PHI];
7967 if (NextPHI) continue; // Already computed!
7968
7969 Value *BEValue = PHI->getIncomingValueForBlock(Latch);
7970 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
7971 }
7972 CurrentIterVals.swap(NextIterVals);
7973 }
7974
7975 // Too many iterations were needed to evaluate.
7976 return getCouldNotCompute();
7977}
7978
7979const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
7980 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values =
7981 ValuesAtScopes[V];
7982 // Check to see if we've folded this expression at this loop before.
7983 for (auto &LS : Values)
7984 if (LS.first == L)
7985 return LS.second ? LS.second : V;
7986
7987 Values.emplace_back(L, nullptr);
7988
7989 // Otherwise compute it.
7990 const SCEV *C = computeSCEVAtScope(V, L);
7991 for (auto &LS : reverse(ValuesAtScopes[V]))
7992 if (LS.first == L) {
7993 LS.second = C;
7994 break;
7995 }
7996 return C;
7997}
7998
7999/// This builds up a Constant using the ConstantExpr interface. That way, we
8000/// will return Constants for objects which aren't represented by a
8001/// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
8002/// Returns NULL if the SCEV isn't representable as a Constant.
8003static Constant *BuildConstantFromSCEV(const SCEV *V) {
8004 switch (static_cast<SCEVTypes>(V->getSCEVType())) {
8005 case scCouldNotCompute:
8006 case scAddRecExpr:
8007 break;
8008 case scConstant:
8009 return cast<SCEVConstant>(V)->getValue();
8010 case scUnknown:
8011 return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue());
8012 case scSignExtend: {
8013 const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V);
8014 if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand()))
8015 return ConstantExpr::getSExt(CastOp, SS->getType());
8016 break;
8017 }
8018 case scZeroExtend: {
8019 const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V);
8020 if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand()))
8021 return ConstantExpr::getZExt(CastOp, SZ->getType());
8022 break;
8023 }
8024 case scTruncate: {
8025 const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V);
8026 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand()))
8027 return ConstantExpr::getTrunc(CastOp, ST->getType());
8028 break;
8029 }
8030 case scAddExpr: {
8031 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V);
8032 if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) {
8033 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
8034 unsigned AS = PTy->getAddressSpace();
8035 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
8036 C = ConstantExpr::getBitCast(C, DestPtrTy);
8037 }
8038 for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) {
8039 Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i));
8040 if (!C2) return nullptr;
8041
8042 // First pointer!
8043 if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) {
8044 unsigned AS = C2->getType()->getPointerAddressSpace();
8045 std::swap(C, C2);
8046 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
8047 // The offsets have been converted to bytes. We can add bytes to an
8048 // i8* by GEP with the byte count in the first index.
8049 C = ConstantExpr::getBitCast(C, DestPtrTy);
8050 }
8051
8052 // Don't bother trying to sum two pointers. We probably can't
8053 // statically compute a load that results from it anyway.
8054 if (C2->getType()->isPointerTy())
8055 return nullptr;
8056
8057 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
8058 if (PTy->getElementType()->isStructTy())
8059 C2 = ConstantExpr::getIntegerCast(
8060 C2, Type::getInt32Ty(C->getContext()), true);
8061 C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2);
8062 } else
8063 C = ConstantExpr::getAdd(C, C2);
8064 }
8065 return C;
8066 }
8067 break;
8068 }
8069 case scMulExpr: {
8070 const SCEVMulExpr *SM = cast<SCEVMulExpr>(V);
8071 if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) {
8072 // Don't bother with pointers at all.
8073 if (C->getType()->isPointerTy()) return nullptr;
8074 for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) {
8075 Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i));
8076 if (!C2 || C2->getType()->isPointerTy()) return nullptr;
8077 C = ConstantExpr::getMul(C, C2);
8078 }
8079 return C;
8080 }
8081 break;
8082 }
8083 case scUDivExpr: {
8084 const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V);
8085 if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS()))
8086 if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS()))
8087 if (LHS->getType() == RHS->getType())
8088 return ConstantExpr::getUDiv(LHS, RHS);
8089 break;
8090 }
8091 case scSMaxExpr:
8092 case scUMaxExpr:
8093 case scSMinExpr:
8094 case scUMinExpr:
8095 break; // TODO: smax, umax, smin, umax.
8096 }
8097 return nullptr;
8098}
8099
8100const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
8101 if (isa<SCEVConstant>(V)) return V;
8102
8103 // If this instruction is evolved from a constant-evolving PHI, compute the
8104 // exit value from the loop without using SCEVs.
8105 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
8106 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
8107 if (PHINode *PN = dyn_cast<PHINode>(I)) {
8108 const Loop *LI = this->LI[I->getParent()];
8109 // Looking for loop exit value.
8110 if (LI && LI->getParentLoop() == L &&
8111 PN->getParent() == LI->getHeader()) {
8112 // Okay, there is no closed form solution for the PHI node. Check
8113 // to see if the loop that contains it has a known backedge-taken
8114 // count. If so, we may be able to force computation of the exit
8115 // value.
8116 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
8117 if (const SCEVConstant *BTCC =
8118 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
8119
8120 // This trivial case can show up in some degenerate cases where
8121 // the incoming IR has not yet been fully simplified.
8122 if (BTCC->getValue()->isZero()) {
8123 Value *InitValue = nullptr;
8124 bool MultipleInitValues = false;
8125 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) {
8126 if (!LI->contains(PN->getIncomingBlock(i))) {
8127 if (!InitValue)
8128 InitValue = PN->getIncomingValue(i);
8129 else if (InitValue != PN->getIncomingValue(i)) {
8130 MultipleInitValues = true;
8131 break;
8132 }
8133 }
8134 }
8135 if (!MultipleInitValues && InitValue)
8136 return getSCEV(InitValue);
8137 }
8138 // Okay, we know how many times the containing loop executes. If
8139 // this is a constant evolving PHI node, get the final value at
8140 // the specified iteration number.
8141 Constant *RV =
8142 getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), LI);
8143 if (RV) return getSCEV(RV);
8144 }
8145 }
8146
8147 // If there is a single-input Phi, evaluate it at our scope. If we can
8148 // prove that this replacement does not break LCSSA form, use new value.
8149 if (PN->getNumOperands() == 1) {
8150 const SCEV *Input = getSCEV(PN->getOperand(0));
8151 const SCEV *InputAtScope = getSCEVAtScope(Input, L);
8152 // TODO: We can generalize it using LI.replacementPreservesLCSSAForm,
8153 // for the simplest case just support constants.
8154 if (isa<SCEVConstant>(InputAtScope)) return InputAtScope;
8155 }
8156 }
8157
8158 // Okay, this is an expression that we cannot symbolically evaluate
8159 // into a SCEV. Check to see if it's possible to symbolically evaluate
8160 // the arguments into constants, and if so, try to constant propagate the
8161 // result. This is particularly useful for computing loop exit values.
8162 if (CanConstantFold(I)) {
8163 SmallVector<Constant *, 4> Operands;
8164 bool MadeImprovement = false;
8165 for (Value *Op : I->operands()) {
8166 if (Constant *C = dyn_cast<Constant>(Op)) {
8167 Operands.push_back(C);
8168 continue;
8169 }
8170
8171 // If any of the operands is non-constant and if they are
8172 // non-integer and non-pointer, don't even try to analyze them
8173 // with scev techniques.
8174 if (!isSCEVable(Op->getType()))
8175 return V;
8176
8177 const SCEV *OrigV = getSCEV(Op);
8178 const SCEV *OpV = getSCEVAtScope(OrigV, L);
8179 MadeImprovement |= OrigV != OpV;
8180
8181 Constant *C = BuildConstantFromSCEV(OpV);
8182 if (!C) return V;
8183 if (C->getType() != Op->getType())
8184 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
8185 Op->getType(),
8186 false),
8187 C, Op->getType());
8188 Operands.push_back(C);
8189 }
8190
8191 // Check to see if getSCEVAtScope actually made an improvement.
8192 if (MadeImprovement) {
8193 Constant *C = nullptr;
8194 const DataLayout &DL = getDataLayout();
8195 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
8196 C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
8197 Operands[1], DL, &TLI);
8198 else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) {
8199 if (!LI->isVolatile())
8200 C = ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
8201 } else
8202 C = ConstantFoldInstOperands(I, Operands, DL, &TLI);
8203 if (!C) return V;
8204 return getSCEV(C);
8205 }
8206 }
8207 }
8208
8209 // This is some other type of SCEVUnknown, just return it.
8210 return V;
8211 }
8212
8213 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
8214 // Avoid performing the look-up in the common case where the specified
8215 // expression has no loop-variant portions.
8216 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
8217 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
8218 if (OpAtScope != Comm->getOperand(i)) {
8219 // Okay, at least one of these operands is loop variant but might be
8220 // foldable. Build a new instance of the folded commutative expression.
8221 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
8222 Comm->op_begin()+i);
8223 NewOps.push_back(OpAtScope);
8224
8225 for (++i; i != e; ++i) {
8226 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
8227 NewOps.push_back(OpAtScope);
8228 }
8229 if (isa<SCEVAddExpr>(Comm))
8230 return getAddExpr(NewOps);
8231 if (isa<SCEVMulExpr>(Comm))
8232 return getMulExpr(NewOps);
8233 if (isa<SCEVMinMaxExpr>(Comm))
8234 return getMinMaxExpr(Comm->getSCEVType(), NewOps);
8235 llvm_unreachable("Unknown commutative SCEV type!");
8236 }
8237 }
8238 // If we got here, all operands are loop invariant.
8239 return Comm;
8240 }
8241
8242 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
8243 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
8244 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
8245 if (LHS == Div->getLHS() && RHS == Div->getRHS())
8246 return Div; // must be loop invariant
8247 return getUDivExpr(LHS, RHS);
8248 }
8249
8250 // If this is a loop recurrence for a loop that does not contain L, then we
8251 // are dealing with the final value computed by the loop.
8252 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
8253 // First, attempt to evaluate each operand.
8254 // Avoid performing the look-up in the common case where the specified
8255 // expression has no loop-variant portions.
8256 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
8257 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
8258 if (OpAtScope == AddRec->getOperand(i))
8259 continue;
8260
8261 // Okay, at least one of these operands is loop variant but might be
8262 // foldable. Build a new instance of the folded commutative expression.
8263 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(),
8264 AddRec->op_begin()+i);
8265 NewOps.push_back(OpAtScope);
8266 for (++i; i != e; ++i)
8267 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
8268
8269 const SCEV *FoldedRec =
8270 getAddRecExpr(NewOps, AddRec->getLoop(),
8271 AddRec->getNoWrapFlags(SCEV::FlagNW));
8272 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
8273 // The addrec may be folded to a nonrecurrence, for example, if the
8274 // induction variable is multiplied by zero after constant folding. Go
8275 // ahead and return the folded value.
8276 if (!AddRec)
8277 return FoldedRec;
8278 break;
8279 }
8280
8281 // If the scope is outside the addrec's loop, evaluate it by using the
8282 // loop exit value of the addrec.
8283 if (!AddRec->getLoop()->contains(L)) {
8284 // To evaluate this recurrence, we need to know how many times the AddRec
8285 // loop iterates. Compute this now.
8286 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
8287 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
8288
8289 // Then, evaluate the AddRec.
8290 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
8291 }
8292
8293 return AddRec;
8294 }
8295
8296 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
8297 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
8298 if (Op == Cast->getOperand())
8299 return Cast; // must be loop invariant
8300 return getZeroExtendExpr(Op, Cast->getType());
8301 }
8302
8303 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
8304 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
8305 if (Op == Cast->getOperand())
8306 return Cast; // must be loop invariant
8307 return getSignExtendExpr(Op, Cast->getType());
8308 }
8309
8310 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
8311 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
8312 if (Op == Cast->getOperand())
8313 return Cast; // must be loop invariant
8314 return getTruncateExpr(Op, Cast->getType());
8315 }
8316
8317 llvm_unreachable("Unknown SCEV type!");
8318}
8319
8320const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
8321 return getSCEVAtScope(getSCEV(V), L);
8322}
8323
8324const SCEV *ScalarEvolution::stripInjectiveFunctions(const SCEV *S) const {
8325 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S))
8326 return stripInjectiveFunctions(ZExt->getOperand());
8327 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S))
8328 return stripInjectiveFunctions(SExt->getOperand());
8329 return S;
8330}
8331
8332/// Finds the minimum unsigned root of the following equation:
8333///
8334/// A * X = B (mod N)
8335///
8336/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
8337/// A and B isn't important.
8338///
8339/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
8340static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B,
8341 ScalarEvolution &SE) {
8342 uint32_t BW = A.getBitWidth();
8343 assert(BW == SE.getTypeSizeInBits(B->getType()));
8344 assert(A != 0 && "A must be non-zero.");
8345
8346 // 1. D = gcd(A, N)
8347 //
8348 // The gcd of A and N may have only one prime factor: 2. The number of
8349 // trailing zeros in A is its multiplicity
8350 uint32_t Mult2 = A.countTrailingZeros();
8351 // D = 2^Mult2
8352
8353 // 2. Check if B is divisible by D.
8354 //
8355 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
8356 // is not less than multiplicity of this prime factor for D.
8357 if (SE.GetMinTrailingZeros(B) < Mult2)
8358 return SE.getCouldNotCompute();
8359
8360 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
8361 // modulo (N / D).
8362 //
8363 // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent
8364 // (N / D) in general. The inverse itself always fits into BW bits, though,
8365 // so we immediately truncate it.
8366 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
8367 APInt Mod(BW + 1, 0);
8368 Mod.setBit(BW - Mult2); // Mod = N / D
8369 APInt I = AD.multiplicativeInverse(Mod).trunc(BW);
8370
8371 // 4. Compute the minimum unsigned root of the equation:
8372 // I * (B / D) mod (N / D)
8373 // To simplify the computation, we factor out the divide by D:
8374 // (I * B mod N) / D
8375 const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2));
8376 return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D);
8377}
8378
8379/// For a given quadratic addrec, generate coefficients of the corresponding
8380/// quadratic equation, multiplied by a common value to ensure that they are
8381/// integers.
8382/// The returned value is a tuple { A, B, C, M, BitWidth }, where
8383/// Ax^2 + Bx + C is the quadratic function, M is the value that A, B and C
8384/// were multiplied by, and BitWidth is the bit width of the original addrec
8385/// coefficients.
8386/// This function returns None if the addrec coefficients are not compile-
8387/// time constants.
8388static Optional<std::tuple<APInt, APInt, APInt, APInt, unsigned>>
8389GetQuadraticEquation(const SCEVAddRecExpr *AddRec) {
8390 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
8391 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
8392 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
8393 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
8394 LLVM_DEBUG(dbgs() << __func__ << ": analyzing quadratic addrec: "
8395 << *AddRec << '\n');
8396
8397 // We currently can only solve this if the coefficients are constants.
8398 if (!LC || !MC || !NC) {
8399 LLVM_DEBUG(dbgs() << __func__ << ": coefficients are not constant\n");
8400 return None;
8401 }
8402
8403 APInt L = LC->getAPInt();
8404 APInt M = MC->getAPInt();
8405 APInt N = NC->getAPInt();
8406 assert(!N.isNullValue() && "This is not a quadratic addrec");
8407
8408 unsigned BitWidth = LC->getAPInt().getBitWidth();
8409 unsigned NewWidth = BitWidth + 1;
8410 LLVM_DEBUG(dbgs() << __func__ << ": addrec coeff bw: "
8411 << BitWidth << '\n');
8412 // The sign-extension (as opposed to a zero-extension) here matches the
8413 // extension used in SolveQuadraticEquationWrap (with the same motivation).
8414 N = N.sext(NewWidth);
8415 M = M.sext(NewWidth);
8416 L = L.sext(NewWidth);
8417
8418 // The increments are M, M+N, M+2N, ..., so the accumulated values are
8419 // L+M, (L+M)+(M+N), (L+M)+(M+N)+(M+2N), ..., that is,
8420 // L+M, L+2M+N, L+3M+3N, ...
8421 // After n iterations the accumulated value Acc is L + nM + n(n-1)/2 N.
8422 //
8423 // The equation Acc = 0 is then
8424 // L + nM + n(n-1)/2 N = 0, or 2L + 2M n + n(n-1) N = 0.
8425 // In a quadratic form it becomes:
8426 // N n^2 + (2M-N) n + 2L = 0.
8427
8428 APInt A = N;
8429 APInt B = 2 * M - A;
8430 APInt C = 2 * L;
8431 APInt T = APInt(NewWidth, 2);
8432 LLVM_DEBUG(dbgs() << __func__ << ": equation " << A << "x^2 + " << B
8433 << "x + " << C << ", coeff bw: " << NewWidth
8434 << ", multiplied by " << T << '\n');
8435 return std::make_tuple(A, B, C, T, BitWidth);
8436}
8437
8438/// Helper function to compare optional APInts:
8439/// (a) if X and Y both exist, return min(X, Y),
8440/// (b) if neither X nor Y exist, return None,
8441/// (c) if exactly one of X and Y exists, return that value.
8442static Optional<APInt> MinOptional(Optional<APInt> X, Optional<APInt> Y) {
8443 if (X.hasValue() && Y.hasValue()) {
8444 unsigned W = std::max(X->getBitWidth(), Y->getBitWidth());
8445 APInt XW = X->sextOrSelf(W);
8446 APInt YW = Y->sextOrSelf(W);
8447 return XW.slt(YW) ? *X : *Y;
8448 }
8449 if (!X.hasValue() && !Y.hasValue())
8450 return None;
8451 return X.hasValue() ? *X : *Y;
8452}
8453
8454/// Helper function to truncate an optional APInt to a given BitWidth.
8455/// When solving addrec-related equations, it is preferable to return a value
8456/// that has the same bit width as the original addrec's coefficients. If the
8457/// solution fits in the original bit width, truncate it (except for i1).
8458/// Returning a value of a different bit width may inhibit some optimizations.
8459///
8460/// In general, a solution to a quadratic equation generated from an addrec
8461/// may require BW+1 bits, where BW is the bit width of the addrec's
8462/// coefficients. The reason is that the coefficients of the quadratic
8463/// equation are BW+1 bits wide (to avoid truncation when converting from
8464/// the addrec to the equation).
8465static Optional<APInt> TruncIfPossible(Optional<APInt> X, unsigned BitWidth) {
8466 if (!X.hasValue())
8467 return None;
8468 unsigned W = X->getBitWidth();
8469 if (BitWidth > 1 && BitWidth < W && X->isIntN(BitWidth))
8470 return X->trunc(BitWidth);
8471 return X;
8472}
8473
8474/// Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n
8475/// iterations. The values L, M, N are assumed to be signed, and they
8476/// should all have the same bit widths.
8477/// Find the least n >= 0 such that c(n) = 0 in the arithmetic modulo 2^BW,
8478/// where BW is the bit width of the addrec's coefficients.
8479/// If the calculated value is a BW-bit integer (for BW > 1), it will be
8480/// returned as such, otherwise the bit width of the returned value may
8481/// be greater than BW.
8482///
8483/// This function returns None if
8484/// (a) the addrec coefficients are not constant, or
8485/// (b) SolveQuadraticEquationWrap was unable to find a solution. For cases
8486/// like x^2 = 5, no integer solutions exist, in other cases an integer
8487/// solution may exist, but SolveQuadraticEquationWrap may fail to find it.
8488static Optional<APInt>
8489SolveQuadraticAddRecExact(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
8490 APInt A, B, C, M;
8491 unsigned BitWidth;
8492 auto T = GetQuadraticEquation(AddRec);
8493 if (!T.hasValue())
8494 return None;
8495
8496 std::tie(A, B, C, M, BitWidth) = *T;
8497 LLVM_DEBUG(dbgs() << __func__ << ": solving for unsigned overflow\n");
8498 Optional<APInt> X = APIntOps::SolveQuadraticEquationWrap(A, B, C, BitWidth+1);
8499 if (!X.hasValue())
8500 return None;
8501
8502 ConstantInt *CX = ConstantInt::get(SE.getContext(), *X);
8503 ConstantInt *V = EvaluateConstantChrecAtConstant(AddRec, CX, SE);
8504 if (!V->isZero())
8505 return None;
8506
8507 return TruncIfPossible(X, BitWidth);
8508}
8509
8510/// Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n
8511/// iterations. The values M, N are assumed to be signed, and they
8512/// should all have the same bit widths.
8513/// Find the least n such that c(n) does not belong to the given range,
8514/// while c(n-1) does.
8515///
8516/// This function returns None if
8517/// (a) the addrec coefficients are not constant, or
8518/// (b) SolveQuadraticEquationWrap was unable to find a solution for the
8519/// bounds of the range.
8520static Optional<APInt>
8521SolveQuadraticAddRecRange(const SCEVAddRecExpr *AddRec,
8522 const ConstantRange &Range, ScalarEvolution &SE) {
8523 assert(AddRec->getOperand(0)->isZero() &&
8524 "Starting value of addrec should be 0");
8525 LLVM_DEBUG(dbgs() << __func__ << ": solving boundary crossing for range "
8526 << Range << ", addrec " << *AddRec << '\n');
8527 // This case is handled in getNumIterationsInRange. Here we can assume that
8528 // we start in the range.
8529 assert(Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType()), 0)) &&
8530 "Addrec's initial value should be in range");
8531
8532 APInt A, B, C, M;
8533 unsigned BitWidth;
8534 auto T = GetQuadraticEquation(AddRec);
8535 if (!T.hasValue())
8536 return None;
8537
8538 // Be careful about the return value: there can be two reasons for not
8539 // returning an actual number. First, if no solutions to the equations
8540 // were found, and second, if the solutions don't leave the given range.
8541 // The first case means that the actual solution is "unknown", the second
8542 // means that it's known, but not valid. If the solution is unknown, we
8543 // cannot make any conclusions.
8544 // Return a pair: the optional solution and a flag indicating if the
8545 // solution was found.
8546 auto SolveForBoundary = [&](APInt Bound) -> std::pair<Optional<APInt>,bool> {
8547 // Solve for signed overflow and unsigned overflow, pick the lower
8548 // solution.
8549 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: checking boundary "
8550 << Bound << " (before multiplying by " << M << ")\n");
8551 Bound *= M; // The quadratic equation multiplier.
8552
8553 Optional<APInt> SO = None;
8554 if (BitWidth > 1) {
8555 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "
8556 "signed overflow\n");
8557 SO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, BitWidth);
8558 }
8559 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "
8560 "unsigned overflow\n");
8561 Optional<APInt> UO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound,
8562 BitWidth+1);
8563
8564 auto LeavesRange = [&] (const APInt &X) {
8565 ConstantInt *C0 = ConstantInt::get(SE.getContext(), X);
8566 ConstantInt *V0 = EvaluateConstantChrecAtConstant(AddRec, C0, SE);
8567 if (Range.contains(V0->getValue()))
8568 return false;
8569 // X should be at least 1, so X-1 is non-negative.
8570 ConstantInt *C1 = ConstantInt::get(SE.getContext(), X-1);
8571 ConstantInt *V1 = EvaluateConstantChrecAtConstant(AddRec, C1, SE);
8572 if (Range.contains(V1->getValue()))
8573 return true;
8574 return false;
8575 };
8576
8577 // If SolveQuadraticEquationWrap returns None, it means that there can
8578 // be a solution, but the function failed to find it. We cannot treat it
8579 // as "no solution".
8580 if (!SO.hasValue() || !UO.hasValue())
8581 return { None, false };
8582
8583 // Check the smaller value first to see if it leaves the range.
8584 // At this point, both SO and UO must have values.
8585 Optional<APInt> Min = MinOptional(SO, UO);
8586 if (LeavesRange(*Min))
8587 return { Min, true };
8588 Optional<APInt> Max = Min == SO ? UO : SO;
8589 if (LeavesRange(*Max))
8590 return { Max, true };
8591
8592 // Solutions were found, but were eliminated, hence the "true".
8593 return { None, true };
8594 };
8595
8596 std::tie(A, B, C, M, BitWidth) = *T;
8597 // Lower bound is inclusive, subtract 1 to represent the exiting value.
8598 APInt Lower = Range.getLower().sextOrSelf(A.getBitWidth()) - 1;
8599 APInt Upper = Range.getUpper().sextOrSelf(A.getBitWidth());
8600 auto SL = SolveForBoundary(Lower);
8601 auto SU = SolveForBoundary(Upper);
8602 // If any of the solutions was unknown, no meaninigful conclusions can
8603 // be made.
8604 if (!SL.second || !SU.second)
8605 return None;
8606
8607 // Claim: The correct solution is not some value between Min and Max.
8608 //
8609 // Justification: Assuming that Min and Max are different values, one of
8610 // them is when the first signed overflow happens, the other is when the
8611 // first unsigned overflow happens. Crossing the range boundary is only
8612 // possible via an overflow (treating 0 as a special case of it, modeling
8613 // an overflow as crossing k*2^W for some k).
8614 //
8615 // The interesting case here is when Min was eliminated as an invalid
8616 // solution, but Max was not. The argument is that if there was another
8617 // overflow between Min and Max, it would also have been eliminated if
8618 // it was considered.
8619 //
8620 // For a given boundary, it is possible to have two overflows of the same
8621 // type (signed/unsigned) without having the other type in between: this
8622 // can happen when the vertex of the parabola is between the iterations
8623 // corresponding to the overflows. This is only possible when the two
8624 // overflows cross k*2^W for the same k. In such case, if the second one
8625 // left the range (and was the first one to do so), the first overflow
8626 // would have to enter the range, which would mean that either we had left
8627 // the range before or that we started outside of it. Both of these cases
8628 // are contradictions.
8629 //
8630 // Claim: In the case where SolveForBoundary returns None, the correct
8631 // solution is not some value between the Max for this boundary and the
8632 // Min of the other boundary.
8633 //
8634 // Justification: Assume that we had such Max_A and Min_B corresponding
8635 // to range boundaries A and B and such that Max_A < Min_B. If there was
8636 // a solution between Max_A and Min_B, it would have to be caused by an
8637 // overflow corresponding to either A or B. It cannot correspond to B,
8638 // since Min_B is the first occurrence of such an overflow. If it
8639 // corresponded to A, it would have to be either a signed or an unsigned
8640 // overflow that is larger than both eliminated overflows for A. But
8641 // between the eliminated overflows and this overflow, the values would
8642 // cover the entire value space, thus crossing the other boundary, which
8643 // is a contradiction.
8644
8645 return TruncIfPossible(MinOptional(SL.first, SU.first), BitWidth);
8646}
8647
8648ScalarEvolution::ExitLimit
8649ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit,
8650 bool AllowPredicates) {
8651
8652 // This is only used for loops with a "x != y" exit test. The exit condition
8653 // is now expressed as a single expression, V = x-y. So the exit test is
8654 // effectively V != 0. We know and take advantage of the fact that this
8655 // expression only being used in a comparison by zero context.
8656
8657 SmallPtrSet<const SCEVPredicate *, 4> Predicates;
8658 // If the value is a constant
8659 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
8660 // If the value is already zero, the branch will execute zero times.
8661 if (C->getValue()->isZero()) return C;
8662 return getCouldNotCompute(); // Otherwise it will loop infinitely.
8663 }
8664
8665 const SCEVAddRecExpr *AddRec =
8666 dyn_cast<SCEVAddRecExpr>(stripInjectiveFunctions(V));
8667
8668 if (!AddRec && AllowPredicates)
8669 // Try to make this an AddRec using runtime tests, in the first X
8670 // iterations of this loop, where X is the SCEV expression found by the
8671 // algorithm below.
8672 AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates);
8673
8674 if (!AddRec || AddRec->getLoop() != L)
8675 return getCouldNotCompute();
8676
8677 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
8678 // the quadratic equation to solve it.
8679 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
8680 // We can only use this value if the chrec ends up with an exact zero
8681 // value at this index. When solving for "X*X != 5", for example, we
8682 // should not accept a root of 2.
8683 if (auto S = SolveQuadraticAddRecExact(AddRec, *this)) {
8684 const auto *R = cast<SCEVConstant>(getConstant(S.getValue()));
8685 return ExitLimit(R, R, false, Predicates);
8686 }
8687 return getCouldNotCompute();
8688 }
8689
8690 // Otherwise we can only handle this if it is affine.
8691 if (!AddRec->isAffine())
8692 return getCouldNotCompute();
8693
8694 // If this is an affine expression, the execution count of this branch is
8695 // the minimum unsigned root of the following equation:
8696 //
8697 // Start + Step*N = 0 (mod 2^BW)
8698 //
8699 // equivalent to:
8700 //
8701 // Step*N = -Start (mod 2^BW)
8702 //
8703 // where BW is the common bit width of Start and Step.
8704
8705 // Get the initial value for the loop.
8706 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
8707 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
8708
8709 // For now we handle only constant steps.
8710 //
8711 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the
8712 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap
8713 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step.
8714 // We have not yet seen any such cases.
8715 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
8716 if (!StepC || StepC->getValue()->isZero())
8717 return getCouldNotCompute();
8718
8719 // For positive steps (counting up until unsigned overflow):
8720 // N = -Start/Step (as unsigned)
8721 // For negative steps (counting down to zero):
8722 // N = Start/-Step
8723 // First compute the unsigned distance from zero in the direction of Step.
8724 bool CountDown = StepC->getAPInt().isNegative();
8725 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
8726
8727 // Handle unitary steps, which cannot wraparound.
8728 // 1*N = -Start; -1*N = Start (mod 2^BW), so:
8729 // N = Distance (as unsigned)
8730 if (StepC->getValue()->isOne() || StepC->getValue()->isMinusOne()) {
8731 APInt MaxBECount = getUnsignedRangeMax(Distance);
8732
8733 // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated,
8734 // we end up with a loop whose backedge-taken count is n - 1. Detect this
8735 // case, and see if we can improve the bound.
8736 //
8737 // Explicitly handling this here is necessary because getUnsignedRange
8738 // isn't context-sensitive; it doesn't know that we only care about the
8739 // range inside the loop.
8740 const SCEV *Zero = getZero(Distance->getType());
8741 const SCEV *One = getOne(Distance->getType());
8742 const SCEV *DistancePlusOne = getAddExpr(Distance, One);
8743 if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) {
8744 // If Distance + 1 doesn't overflow, we can compute the maximum distance
8745 // as "unsigned_max(Distance + 1) - 1".
8746 ConstantRange CR = getUnsignedRange(DistancePlusOne);
8747 MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1);
8748 }
8749 return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates);
8750 }
8751
8752 // If the condition controls loop exit (the loop exits only if the expression
8753 // is true) and the addition is no-wrap we can use unsigned divide to
8754 // compute the backedge count. In this case, the step may not divide the
8755 // distance, but we don't care because if the condition is "missed" the loop
8756 // will have undefined behavior due to wrapping.
8757 if (ControlsExit && AddRec->hasNoSelfWrap() &&
8758 loopHasNoAbnormalExits(AddRec->getLoop())) {
8759 const SCEV *Exact =
8760 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
8761 const SCEV *Max =
8762 Exact == getCouldNotCompute()
8763 ? Exact
8764 : getConstant(getUnsignedRangeMax(Exact));
8765 return ExitLimit(Exact, Max, false, Predicates);
8766 }
8767
8768 // Solve the general equation.
8769 const SCEV *E = SolveLinEquationWithOverflow(StepC->getAPInt(),
8770 getNegativeSCEV(Start), *this);
8771 const SCEV *M = E == getCouldNotCompute()
8772 ? E
8773 : getConstant(getUnsignedRangeMax(E));
8774 return ExitLimit(E, M, false, Predicates);
8775}
8776
8777ScalarEvolution::ExitLimit
8778ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) {
8779 // Loops that look like: while (X == 0) are very strange indeed. We don't
8780 // handle them yet except for the trivial case. This could be expanded in the
8781 // future as needed.
8782
8783 // If the value is a constant, check to see if it is known to be non-zero
8784 // already. If so, the backedge will execute zero times.
8785 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
8786 if (!C->getValue()->isZero())
8787 return getZero(C->getType());
8788 return getCouldNotCompute(); // Otherwise it will loop infinitely.
8789 }
8790
8791 // We could implement others, but I really doubt anyone writes loops like
8792 // this, and if they did, they would already be constant folded.
8793 return getCouldNotCompute();
8794}
8795
8796std::pair<BasicBlock *, BasicBlock *>
8797ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
8798 // If the block has a unique predecessor, then there is no path from the
8799 // predecessor to the block that does not go through the direct edge
8800 // from the predecessor to the block.
8801 if (BasicBlock *Pred = BB->getSinglePredecessor())
8802 return {Pred, BB};
8803
8804 // A loop's header is defined to be a block that dominates the loop.
8805 // If the header has a unique predecessor outside the loop, it must be
8806 // a block that has exactly one successor that can reach the loop.
8807 if (Loop *L = LI.getLoopFor(BB))
8808 return {L->getLoopPredecessor(), L->getHeader()};
8809
8810 return {nullptr, nullptr};
8811}
8812
8813/// SCEV structural equivalence is usually sufficient for testing whether two
8814/// expressions are equal, however for the purposes of looking for a condition
8815/// guarding a loop, it can be useful to be a little more general, since a
8816/// front-end may have replicated the controlling expression.
8817static bool HasSameValue(const SCEV *A, const SCEV *B) {
8818 // Quick check to see if they are the same SCEV.
8819 if (A == B) return true;
8820
8821 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) {
8822 // Not all instructions that are "identical" compute the same value. For
8823 // instance, two distinct alloca instructions allocating the same type are
8824 // identical and do not read memory; but compute distinct values.
8825 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A));
8826 };
8827
8828 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
8829 // two different instructions with the same value. Check for this case.
8830 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
8831 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
8832 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
8833 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
8834 if (ComputesEqualValues(AI, BI))
8835 return true;
8836
8837 // Otherwise assume they may have a different value.
8838 return false;
8839}
8840
8841bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
8842 const SCEV *&LHS, const SCEV *&RHS,
8843 unsigned Depth) {
8844 bool Changed = false;
8845 // Simplifies ICMP to trivial true or false by turning it into '0 == 0' or
8846 // '0 != 0'.
8847 auto TrivialCase = [&](bool TriviallyTrue) {
8848 LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
8849 Pred = TriviallyTrue ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
8850 return true;
8851 };
8852 // If we hit the max recursion limit bail out.
8853 if (Depth >= 3)
8854 return false;
8855
8856 // Canonicalize a constant to the right side.
8857 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
8858 // Check for both operands constant.
8859 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
8860 if (ConstantExpr::getICmp(Pred,
8861 LHSC->getValue(),
8862 RHSC->getValue())->isNullValue())
8863 return TrivialCase(false);
8864 else
8865 return TrivialCase(true);
8866 }
8867 // Otherwise swap the operands to put the constant on the right.
8868 std::swap(LHS, RHS);
8869 Pred = ICmpInst::getSwappedPredicate(Pred);
8870 Changed = true;
8871 }
8872
8873 // If we're comparing an addrec with a value which is loop-invariant in the
8874 // addrec's loop, put the addrec on the left. Also make a dominance check,
8875 // as both operands could be addrecs loop-invariant in each other's loop.
8876 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
8877 const Loop *L = AR->getLoop();
8878 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
8879 std::swap(LHS, RHS);
8880 Pred = ICmpInst::getSwappedPredicate(Pred);
8881 Changed = true;
8882 }
8883 }
8884
8885 // If there's a constant operand, canonicalize comparisons with boundary
8886 // cases, and canonicalize *-or-equal comparisons to regular comparisons.
8887 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
8888 const APInt &RA = RC->getAPInt();
8889
8890 bool SimplifiedByConstantRange = false;
8891
8892 if (!ICmpInst::isEquality(Pred)) {
8893 ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA);
8894 if (ExactCR.isFullSet())
8895 return TrivialCase(true);
8896 else if (ExactCR.isEmptySet())
8897 return TrivialCase(false);
8898
8899 APInt NewRHS;
8900 CmpInst::Predicate NewPred;
8901 if (ExactCR.getEquivalentICmp(NewPred, NewRHS) &&
8902 ICmpInst::isEquality(NewPred)) {
8903 // We were able to convert an inequality to an equality.
8904 Pred = NewPred;
8905 RHS = getConstant(NewRHS);
8906 Changed = SimplifiedByConstantRange = true;
8907 }
8908 }
8909
8910 if (!SimplifiedByConstantRange) {
8911 switch (Pred) {
8912 default:
8913 break;
8914 case ICmpInst::ICMP_EQ:
8915 case ICmpInst::ICMP_NE:
8916 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b.
8917 if (!RA)
8918 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS))
8919 if (const SCEVMulExpr *ME =
8920 dyn_cast<SCEVMulExpr>(AE->getOperand(0)))
8921 if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 &&
8922 ME->getOperand(0)->isAllOnesValue()) {
8923 RHS = AE->getOperand(1);
8924 LHS = ME->getOperand(1);
8925 Changed = true;
8926 }
8927 break;
8928
8929
8930 // The "Should have been caught earlier!" messages refer to the fact
8931 // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above
8932 // should have fired on the corresponding cases, and canonicalized the
8933 // check to trivial case.
8934
8935 case ICmpInst::ICMP_UGE:
8936 assert(!RA.isMinValue() && "Should have been caught earlier!");
8937 Pred = ICmpInst::ICMP_UGT;
8938 RHS = getConstant(RA - 1);
8939 Changed = true;
8940 break;
8941 case ICmpInst::ICMP_ULE:
8942 assert(!RA.isMaxValue() && "Should have been caught earlier!");
8943 Pred = ICmpInst::ICMP_ULT;
8944 RHS = getConstant(RA + 1);
8945 Changed = true;
8946 break;
8947 case ICmpInst::ICMP_SGE:
8948 assert(!RA.isMinSignedValue() && "Should have been caught earlier!");
8949 Pred = ICmpInst::ICMP_SGT;
8950 RHS = getConstant(RA - 1);
8951 Changed = true;
8952 break;
8953 case ICmpInst::ICMP_SLE:
8954 assert(!RA.isMaxSignedValue() && "Should have been caught earlier!");
8955 Pred = ICmpInst::ICMP_SLT;
8956 RHS = getConstant(RA + 1);
8957 Changed = true;
8958 break;
8959 }
8960 }
8961 }
8962
8963 // Check for obvious equality.
8964 if (HasSameValue(LHS, RHS)) {
8965 if (ICmpInst::isTrueWhenEqual(Pred))
8966 return TrivialCase(true);
8967 if (ICmpInst::isFalseWhenEqual(Pred))
8968 return TrivialCase(false);
8969 }
8970
8971 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
8972 // adding or subtracting 1 from one of the operands.
8973 switch (Pred) {
8974 case ICmpInst::ICMP_SLE:
8975 if (!getSignedRangeMax(RHS).isMaxSignedValue()) {
8976 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
8977 SCEV::FlagNSW);
8978 Pred = ICmpInst::ICMP_SLT;
8979 Changed = true;
8980 } else if (!getSignedRangeMin(LHS).isMinSignedValue()) {
8981 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
8982 SCEV::FlagNSW);
8983 Pred = ICmpInst::ICMP_SLT;
8984 Changed = true;
8985 }
8986 break;
8987 case ICmpInst::ICMP_SGE:
8988 if (!getSignedRangeMin(RHS).isMinSignedValue()) {
8989 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
8990 SCEV::FlagNSW);
8991 Pred = ICmpInst::ICMP_SGT;
8992 Changed = true;
8993 } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) {
8994 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
8995 SCEV::FlagNSW);
8996 Pred = ICmpInst::ICMP_SGT;
8997 Changed = true;
8998 }
8999 break;
9000 case ICmpInst::ICMP_ULE:
9001 if (!getUnsignedRangeMax(RHS).isMaxValue()) {
9002 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
9003 SCEV::FlagNUW);
9004 Pred = ICmpInst::ICMP_ULT;
9005 Changed = true;
9006 } else if (!getUnsignedRangeMin(LHS).isMinValue()) {
9007 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS);
9008 Pred = ICmpInst::ICMP_ULT;
9009 Changed = true;
9010 }
9011 break;
9012 case ICmpInst::ICMP_UGE:
9013 if (!getUnsignedRangeMin(RHS).isMinValue()) {
9014 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
9015 Pred = ICmpInst::ICMP_UGT;
9016 Changed = true;
9017 } else if (!getUnsignedRangeMax(LHS).isMaxValue()) {
9018 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
9019 SCEV::FlagNUW);
9020 Pred = ICmpInst::ICMP_UGT;
9021 Changed = true;
9022 }
9023 break;
9024 default:
9025 break;
9026 }
9027
9028 // TODO: More simplifications are possible here.
9029
9030 // Recursively simplify until we either hit a recursion limit or nothing
9031 // changes.
9032 if (Changed)
9033 return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1);
9034
9035 return Changed;
9036}
9037
9038bool ScalarEvolution::isKnownNegative(const SCEV *S) {
9039 return getSignedRangeMax(S).isNegative();
9040}
9041
9042bool ScalarEvolution::isKnownPositive(const SCEV *S) {
9043 return getSignedRangeMin(S).isStrictlyPositive();
9044}
9045
9046bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
9047 return !getSignedRangeMin(S).isNegative();
9048}
9049
9050bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
9051 return !getSignedRangeMax(S).isStrictlyPositive();
9052}
9053
9054bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
9055 return isKnownNegative(S) || isKnownPositive(S);
9056}
9057
9058std::pair<const SCEV *, const SCEV *>
9059ScalarEvolution::SplitIntoInitAndPostInc(const Loop *L, const SCEV *S) {
9060 // Compute SCEV on entry of loop L.
9061 const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *this);
9062 if (Start == getCouldNotCompute())
9063 return { Start, Start };
9064 // Compute post increment SCEV for loop L.
9065 const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, *this);
9066 assert(PostInc != getCouldNotCompute() && "Unexpected could not compute");
9067 return { Start, PostInc };
9068}
9069
9070bool ScalarEvolution::isKnownViaInduction(ICmpInst::Predicate Pred,
9071 const SCEV *LHS, const SCEV *RHS) {
9072 // First collect all loops.
9073 SmallPtrSet<const Loop *, 8> LoopsUsed;
9074 getUsedLoops(LHS, LoopsUsed);
9075 getUsedLoops(RHS, LoopsUsed);
9076
9077 if (LoopsUsed.empty())
9078 return false;
9079
9080 // Domination relationship must be a linear order on collected loops.
9081#ifndef NDEBUG
9082 for (auto *L1 : LoopsUsed)
9083 for (auto *L2 : LoopsUsed)
9084 assert((DT.dominates(L1->getHeader(), L2->getHeader()) ||
9085 DT.dominates(L2->getHeader(), L1->getHeader())) &&
9086 "Domination relationship is not a linear order");
9087#endif
9088
9089 const Loop *MDL =
9090 *std::max_element(LoopsUsed.begin(), LoopsUsed.end(),
9091 [&](const Loop *L1, const Loop *L2) {
9092 return DT.properlyDominates(L1->getHeader(), L2->getHeader());
9093 });
9094
9095 // Get init and post increment value for LHS.
9096 auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS);
9097 // if LHS contains unknown non-invariant SCEV then bail out.
9098 if (SplitLHS.first == getCouldNotCompute())
9099 return false;
9100 assert (SplitLHS.second != getCouldNotCompute() && "Unexpected CNC");
9101 // Get init and post increment value for RHS.
9102 auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS);
9103 // if RHS contains unknown non-invariant SCEV then bail out.
9104 if (SplitRHS.first == getCouldNotCompute())
9105 return false;
9106 assert (SplitRHS.second != getCouldNotCompute() && "Unexpected CNC");
9107 // It is possible that init SCEV contains an invariant load but it does
9108 // not dominate MDL and is not available at MDL loop entry, so we should
9109 // check it here.
9110 if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) ||
9111 !isAvailableAtLoopEntry(SplitRHS.first, MDL))
9112 return false;
9113
9114 return isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first) &&
9115 isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second,
9116 SplitRHS.second);
9117}
9118
9119bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
9120 const SCEV *LHS, const SCEV *RHS) {
9121 // Canonicalize the inputs first.
9122 (void)SimplifyICmpOperands(Pred, LHS, RHS);
9123
9124 if (isKnownViaInduction(Pred, LHS, RHS))
9125 return true;
9126
9127 if (isKnownPredicateViaSplitting(Pred, LHS, RHS))
9128 return true;
9129
9130 // Otherwise see what can be done with some simple reasoning.
9131 return isKnownViaNonRecursiveReasoning(Pred, LHS, RHS);
9132}
9133
9134bool ScalarEvolution::isKnownOnEveryIteration(ICmpInst::Predicate Pred,
9135 const SCEVAddRecExpr *LHS,
9136 const SCEV *RHS) {
9137 const Loop *L = LHS->getLoop();
9138 return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) &&
9139 isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS);
9140}
9141
9142bool ScalarEvolution::isMonotonicPredicate(const SCEVAddRecExpr *LHS,
9143 ICmpInst::Predicate Pred,
9144 bool &Increasing) {
9145 bool Result = isMonotonicPredicateImpl(LHS, Pred, Increasing);
9146
9147#ifndef NDEBUG
9148 // Verify an invariant: inverting the predicate should turn a monotonically
9149 // increasing change to a monotonically decreasing one, and vice versa.
9150 bool IncreasingSwapped;
9151 bool ResultSwapped = isMonotonicPredicateImpl(
9152 LHS, ICmpInst::getSwappedPredicate(Pred), IncreasingSwapped);
9153
9154 assert(Result == ResultSwapped && "should be able to analyze both!");
9155 if (ResultSwapped)
9156 assert(Increasing == !IncreasingSwapped &&
9157 "monotonicity should flip as we flip the predicate");
9158#endif
9159
9160 return Result;
9161}
9162
9163bool ScalarEvolution::isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS,
9164 ICmpInst::Predicate Pred,
9165 bool &Increasing) {
9166
9167 // A zero step value for LHS means the induction variable is essentially a
9168 // loop invariant value. We don't really depend on the predicate actually
9169 // flipping from false to true (for increasing predicates, and the other way
9170 // around for decreasing predicates), all we care about is that *if* the
9171 // predicate changes then it only changes from false to true.
9172 //
9173 // A zero step value in itself is not very useful, but there may be places
9174 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be
9175 // as general as possible.
9176
9177 switch (Pred) {
9178 default:
9179 return false; // Conservative answer
9180
9181 case ICmpInst::ICMP_UGT:
9182 case ICmpInst::ICMP_UGE:
9183 case ICmpInst::ICMP_ULT:
9184 case ICmpInst::ICMP_ULE:
9185 if (!LHS->hasNoUnsignedWrap())
9186 return false;
9187
9188 Increasing = Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE;
9189 return true;
9190
9191 case ICmpInst::ICMP_SGT:
9192 case ICmpInst::ICMP_SGE:
9193 case ICmpInst::ICMP_SLT:
9194 case ICmpInst::ICMP_SLE: {
9195 if (!LHS->hasNoSignedWrap())
9196 return false;
9197
9198 const SCEV *Step = LHS->getStepRecurrence(*this);
9199
9200 if (isKnownNonNegative(Step)) {
9201 Increasing = Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE;
9202 return true;
9203 }
9204
9205 if (isKnownNonPositive(Step)) {
9206 Increasing = Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE;
9207 return true;
9208 }
9209
9210 return false;
9211 }
9212
9213 }
9214
9215 llvm_unreachable("switch has default clause!");
9216}
9217
9218bool ScalarEvolution::isLoopInvariantPredicate(
9219 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
9220 ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS,
9221 const SCEV *&InvariantRHS) {
9222
9223 // If there is a loop-invariant, force it into the RHS, otherwise bail out.
9224 if (!isLoopInvariant(RHS, L)) {
9225 if (!isLoopInvariant(LHS, L))
9226 return false;
9227
9228 std::swap(LHS, RHS);
9229 Pred = ICmpInst::getSwappedPredicate(Pred);
9230 }
9231
9232 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS);
9233 if (!ArLHS || ArLHS->getLoop() != L)
9234 return false;
9235
9236 bool Increasing;
9237 if (!isMonotonicPredicate(ArLHS, Pred, Increasing))
9238 return false;
9239
9240 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to
9241 // true as the loop iterates, and the backedge is control dependent on
9242 // "ArLHS `Pred` RHS" == true then we can reason as follows:
9243 //
9244 // * if the predicate was false in the first iteration then the predicate
9245 // is never evaluated again, since the loop exits without taking the
9246 // backedge.
9247 // * if the predicate was true in the first iteration then it will
9248 // continue to be true for all future iterations since it is
9249 // monotonically increasing.
9250 //
9251 // For both the above possibilities, we can replace the loop varying
9252 // predicate with its value on the first iteration of the loop (which is
9253 // loop invariant).
9254 //
9255 // A similar reasoning applies for a monotonically decreasing predicate, by
9256 // replacing true with false and false with true in the above two bullets.
9257
9258 auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred);
9259
9260 if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS))
9261 return false;
9262
9263 InvariantPred = Pred;
9264 InvariantLHS = ArLHS->getStart();
9265 InvariantRHS = RHS;
9266 return true;
9267}
9268
9269bool ScalarEvolution::isKnownPredicateViaConstantRanges(
9270 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) {
9271 if (HasSameValue(LHS, RHS))
9272 return ICmpInst::isTrueWhenEqual(Pred);
9273
9274 // This code is split out from isKnownPredicate because it is called from
9275 // within isLoopEntryGuardedByCond.
9276
9277 auto CheckRanges =
9278 [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) {
9279 return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS)
9280 .contains(RangeLHS);
9281 };
9282
9283 // The check at the top of the function catches the case where the values are
9284 // known to be equal.
9285 if (Pred == CmpInst::ICMP_EQ)
9286 return false;
9287
9288 if (Pred == CmpInst::ICMP_NE)
9289 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) ||
9290 CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) ||
9291 isKnownNonZero(getMinusSCEV(LHS, RHS));
9292
9293 if (CmpInst::isSigned(Pred))
9294 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS));
9295
9296 return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS));
9297}
9298
9299bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred,
9300 const SCEV *LHS,
9301 const SCEV *RHS) {
9302 // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer.
9303 // Return Y via OutY.
9304 auto MatchBinaryAddToConst =
9305 [this](const SCEV *Result, const SCEV *X, APInt &OutY,
9306 SCEV::NoWrapFlags ExpectedFlags) {
9307 const SCEV *NonConstOp, *ConstOp;
9308 SCEV::NoWrapFlags FlagsPresent;
9309
9310 if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) ||
9311 !isa<SCEVConstant>(ConstOp) || NonConstOp != X)
9312 return false;
9313
9314 OutY = cast<SCEVConstant>(ConstOp)->getAPInt();
9315 return (FlagsPresent & ExpectedFlags) == ExpectedFlags;
9316 };
9317
9318 APInt C;
9319
9320 switch (Pred) {
9321 default:
9322 break;
9323
9324 case ICmpInst::ICMP_SGE:
9325 std::swap(LHS, RHS);
9326 LLVM_FALLTHROUGH;
9327 case ICmpInst::ICMP_SLE:
9328 // X s<= (X + C)<nsw> if C >= 0
9329 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative())
9330 return true;
9331
9332 // (X + C)<nsw> s<= X if C <= 0
9333 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) &&
9334 !C.isStrictlyPositive())
9335 return true;
9336 break;
9337
9338 case ICmpInst::ICMP_SGT:
9339 std::swap(LHS, RHS);
9340 LLVM_FALLTHROUGH;
9341 case ICmpInst::ICMP_SLT:
9342 // X s< (X + C)<nsw> if C > 0
9343 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) &&
9344 C.isStrictlyPositive())
9345 return true;
9346
9347 // (X + C)<nsw> s< X if C < 0
9348 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative())
9349 return true;
9350 break;
9351 }
9352
9353 return false;
9354}
9355
9356bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred,
9357 const SCEV *LHS,
9358 const SCEV *RHS) {
9359 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate)
9360 return false;
9361
9362 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on
9363 // the stack can result in exponential time complexity.
9364 SaveAndRestore<bool> Restore(ProvingSplitPredicate, true);
9365
9366 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L
9367 //
9368 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use
9369 // isKnownPredicate. isKnownPredicate is more powerful, but also more
9370 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the
9371 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to
9372 // use isKnownPredicate later if needed.
9373 return isKnownNonNegative(RHS) &&
9374 isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) &&
9375 isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS);
9376}
9377
9378bool ScalarEvolution::isImpliedViaGuard(BasicBlock *BB,
9379 ICmpInst::Predicate Pred,
9380 const SCEV *LHS, const SCEV *RHS) {
9381 // No need to even try if we know the module has no guards.
9382 if (!HasGuards)
9383 return false;
9384
9385 return any_of(*BB, [&](Instruction &I) {
9386 using namespace llvm::PatternMatch;
9387
9388 Value *Condition;
9389 return match(&I, m_Intrinsic<Intrinsic::experimental_guard>(
9390 m_Value(Condition))) &&
9391 isImpliedCond(Pred, LHS, RHS, Condition, false);
9392 });
9393}
9394
9395/// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
9396/// protected by a conditional between LHS and RHS. This is used to
9397/// to eliminate casts.
9398bool
9399ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
9400 ICmpInst::Predicate Pred,
9401 const SCEV *LHS, const SCEV *RHS) {
9402 // Interpret a null as meaning no loop, where there is obviously no guard
9403 // (interprocedural conditions notwithstanding).
9404 if (!L) return true;
9405
9406 if (VerifyIR)
9407 assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) &&
9408 "This cannot be done on broken IR!");
9409
9410
9411 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
9412 return true;
9413
9414 BasicBlock *Latch = L->getLoopLatch();
9415 if (!Latch)
9416 return false;
9417
9418 BranchInst *LoopContinuePredicate =
9419 dyn_cast<BranchInst>(Latch->getTerminator());
9420 if (LoopContinuePredicate && LoopContinuePredicate->isConditional() &&
9421 isImpliedCond(Pred, LHS, RHS,
9422 LoopContinuePredicate->getCondition(),
9423 LoopContinuePredicate->getSuccessor(0) != L->getHeader()))
9424 return true;
9425
9426 // We don't want more than one activation of the following loops on the stack
9427 // -- that can lead to O(n!) time complexity.
9428 if (WalkingBEDominatingConds)
9429 return false;
9430
9431 SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true);
9432
9433 // See if we can exploit a trip count to prove the predicate.
9434 const auto &BETakenInfo = getBackedgeTakenInfo(L);
9435 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this);
9436 if (LatchBECount != getCouldNotCompute()) {
9437 // We know that Latch branches back to the loop header exactly
9438 // LatchBECount times. This means the backdege condition at Latch is
9439 // equivalent to "{0,+,1} u< LatchBECount".
9440 Type *Ty = LatchBECount->getType();
9441 auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW);
9442 const SCEV *LoopCounter =
9443 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags);
9444 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter,
9445 LatchBECount))
9446 return true;
9447 }
9448
9449 // Check conditions due to any @llvm.assume intrinsics.
9450 for (auto &AssumeVH : AC.assumptions()) {
9451 if (!AssumeVH)
9452 continue;
9453 auto *CI = cast<CallInst>(AssumeVH);
9454 if (!DT.dominates(CI, Latch->getTerminator()))
9455 continue;
9456
9457 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
9458 return true;
9459 }
9460
9461 // If the loop is not reachable from the entry block, we risk running into an
9462 // infinite loop as we walk up into the dom tree. These loops do not matter
9463 // anyway, so we just return a conservative answer when we see them.
9464 if (!DT.isReachableFromEntry(L->getHeader()))
9465 return false;
9466
9467 if (isImpliedViaGuard(Latch, Pred, LHS, RHS))
9468 return true;
9469
9470 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()];
9471 DTN != HeaderDTN; DTN = DTN->getIDom()) {
9472 assert(DTN && "should reach the loop header before reaching the root!");
9473
9474 BasicBlock *BB = DTN->getBlock();
9475 if (isImpliedViaGuard(BB, Pred, LHS, RHS))
9476 return true;
9477
9478 BasicBlock *PBB = BB->getSinglePredecessor();
9479 if (!PBB)
9480 continue;
9481
9482 BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator());
9483 if (!ContinuePredicate || !ContinuePredicate->isConditional())
9484 continue;
9485
9486 Value *Condition = ContinuePredicate->getCondition();
9487
9488 // If we have an edge `E` within the loop body that dominates the only
9489 // latch, the condition guarding `E` also guards the backedge. This
9490 // reasoning works only for loops with a single latch.
9491
9492 BasicBlockEdge DominatingEdge(PBB, BB);
9493 if (DominatingEdge.isSingleEdge()) {
9494 // We're constructively (and conservatively) enumerating edges within the
9495 // loop body that dominate the latch. The dominator tree better agree
9496 // with us on this:
9497 assert(DT.dominates(DominatingEdge, Latch) && "should be!");
9498
9499 if (isImpliedCond(Pred, LHS, RHS, Condition,
9500 BB != ContinuePredicate->getSuccessor(0)))
9501 return true;
9502 }
9503 }
9504
9505 return false;
9506}
9507
9508bool
9509ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
9510 ICmpInst::Predicate Pred,
9511 const SCEV *LHS, const SCEV *RHS) {
9512 // Interpret a null as meaning no loop, where there is obviously no guard
9513 // (interprocedural conditions notwithstanding).
9514 if (!L) return false;
9515
9516 if (VerifyIR)
9517 assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) &&
9518 "This cannot be done on broken IR!");
9519
9520 // Both LHS and RHS must be available at loop entry.
9521 assert(isAvailableAtLoopEntry(LHS, L) &&
9522 "LHS is not available at Loop Entry");
9523 assert(isAvailableAtLoopEntry(RHS, L) &&
9524 "RHS is not available at Loop Entry");
9525
9526 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
9527 return true;
9528
9529 // If we cannot prove strict comparison (e.g. a > b), maybe we can prove
9530 // the facts (a >= b && a != b) separately. A typical situation is when the
9531 // non-strict comparison is known from ranges and non-equality is known from
9532 // dominating predicates. If we are proving strict comparison, we always try
9533 // to prove non-equality and non-strict comparison separately.
9534 auto NonStrictPredicate = ICmpInst::getNonStrictPredicate(Pred);
9535 const bool ProvingStrictComparison = (Pred != NonStrictPredicate);
9536 bool ProvedNonStrictComparison = false;
9537 bool ProvedNonEquality = false;
9538
9539 if (ProvingStrictComparison) {
9540 ProvedNonStrictComparison =
9541 isKnownViaNonRecursiveReasoning(NonStrictPredicate, LHS, RHS);
9542 ProvedNonEquality =
9543 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_NE, LHS, RHS);
9544 if (ProvedNonStrictComparison && ProvedNonEquality)
9545 return true;
9546 }
9547
9548 // Try to prove (Pred, LHS, RHS) using isImpliedViaGuard.
9549 auto ProveViaGuard = [&](BasicBlock *Block) {
9550 if (isImpliedViaGuard(Block, Pred, LHS, RHS))
9551 return true;
9552 if (ProvingStrictComparison) {
9553 if (!ProvedNonStrictComparison)
9554 ProvedNonStrictComparison =
9555 isImpliedViaGuard(Block, NonStrictPredicate, LHS, RHS);
9556 if (!ProvedNonEquality)
9557 ProvedNonEquality =
9558 isImpliedViaGuard(Block, ICmpInst::ICMP_NE, LHS, RHS);
9559 if (ProvedNonStrictComparison && ProvedNonEquality)
9560 return true;
9561 }
9562 return false;
9563 };
9564
9565 // Try to prove (Pred, LHS, RHS) using isImpliedCond.
9566 auto ProveViaCond = [&](Value *Condition, bool Inverse) {
9567 if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse))
9568 return true;
9569 if (ProvingStrictComparison) {
9570 if (!ProvedNonStrictComparison)
9571 ProvedNonStrictComparison =
9572 isImpliedCond(NonStrictPredicate, LHS, RHS, Condition, Inverse);
9573 if (!ProvedNonEquality)
9574 ProvedNonEquality =
9575 isImpliedCond(ICmpInst::ICMP_NE, LHS, RHS, Condition, Inverse);
9576 if (ProvedNonStrictComparison && ProvedNonEquality)
9577 return true;
9578 }
9579 return false;
9580 };
9581
9582 // Starting at the loop predecessor, climb up the predecessor chain, as long
9583 // as there are predecessors that can be found that have unique successors
9584 // leading to the original header.
9585 for (std::pair<BasicBlock *, BasicBlock *>
9586 Pair(L->getLoopPredecessor(), L->getHeader());
9587 Pair.first;
9588 Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
9589
9590 if (ProveViaGuard(Pair.first))
9591 return true;
9592
9593 BranchInst *LoopEntryPredicate =
9594 dyn_cast<BranchInst>(Pair.first->getTerminator());
9595 if (!LoopEntryPredicate ||
9596 LoopEntryPredicate->isUnconditional())
9597 continue;
9598
9599 if (ProveViaCond(LoopEntryPredicate->getCondition(),
9600 LoopEntryPredicate->getSuccessor(0) != Pair.second))
9601 return true;
9602 }
9603
9604 // Check conditions due to any @llvm.assume intrinsics.
9605 for (auto &AssumeVH : AC.assumptions()) {
9606 if (!AssumeVH)
9607 continue;
9608 auto *CI = cast<CallInst>(AssumeVH);
9609 if (!DT.dominates(CI, L->getHeader()))
9610 continue;
9611
9612 if (ProveViaCond(CI->getArgOperand(0), false))
9613 return true;
9614 }
9615
9616 return false;
9617}
9618
9619bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred,
9620 const SCEV *LHS, const SCEV *RHS,
9621 Value *FoundCondValue,
9622 bool Inverse) {
9623 if (!PendingLoopPredicates.insert(FoundCondValue).second)
9624 return false;
9625
9626 auto ClearOnExit =
9627 make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); });
9628
9629 // Recursively handle And and Or conditions.
9630 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) {
9631 if (BO->getOpcode() == Instruction::And) {
9632 if (!Inverse)
9633 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
9634 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
9635 } else if (BO->getOpcode() == Instruction::Or) {
9636 if (Inverse)
9637 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
9638 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
9639 }
9640 }
9641
9642 ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
9643 if (!ICI) return false;
9644
9645 // Now that we found a conditional branch that dominates the loop or controls
9646 // the loop latch. Check to see if it is the comparison we are looking for.
9647 ICmpInst::Predicate FoundPred;
9648 if (Inverse)
9649 FoundPred = ICI->getInversePredicate();
9650 else
9651 FoundPred = ICI->getPredicate();
9652
9653 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
9654 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
9655
9656 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS);
9657}
9658
9659bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS,
9660 const SCEV *RHS,
9661 ICmpInst::Predicate FoundPred,
9662 const SCEV *FoundLHS,
9663 const SCEV *FoundRHS) {
9664 // Balance the types.
9665 if (getTypeSizeInBits(LHS->getType()) <
9666 getTypeSizeInBits(FoundLHS->getType())) {
9667 if (CmpInst::isSigned(Pred)) {
9668 LHS = getSignExtendExpr(LHS, FoundLHS->getType());
9669 RHS = getSignExtendExpr(RHS, FoundLHS->getType());
9670 } else {
9671 LHS = getZeroExtendExpr(LHS, FoundLHS->getType());
9672 RHS = getZeroExtendExpr(RHS, FoundLHS->getType());
9673 }
9674 } else if (getTypeSizeInBits(LHS->getType()) >
9675 getTypeSizeInBits(FoundLHS->getType())) {
9676 if (CmpInst::isSigned(FoundPred)) {
9677 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
9678 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
9679 } else {
9680 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
9681 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
9682 }
9683 }
9684
9685 // Canonicalize the query to match the way instcombine will have
9686 // canonicalized the comparison.
9687 if (SimplifyICmpOperands(Pred, LHS, RHS))
9688 if (LHS == RHS)
9689 return CmpInst::isTrueWhenEqual(Pred);
9690 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
9691 if (FoundLHS == FoundRHS)
9692 return CmpInst::isFalseWhenEqual(FoundPred);
9693
9694 // Check to see if we can make the LHS or RHS match.
9695 if (LHS == FoundRHS || RHS == FoundLHS) {
9696 if (isa<SCEVConstant>(RHS)) {
9697 std::swap(FoundLHS, FoundRHS);
9698 FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
9699 } else {
9700 std::swap(LHS, RHS);
9701 Pred = ICmpInst::getSwappedPredicate(Pred);
9702 }
9703 }
9704
9705 // Check whether the found predicate is the same as the desired predicate.
9706 if (FoundPred == Pred)
9707 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
9708
9709 // Check whether swapping the found predicate makes it the same as the
9710 // desired predicate.
9711 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
9712 if (isa<SCEVConstant>(RHS))
9713 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
9714 else
9715 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred),
9716 RHS, LHS, FoundLHS, FoundRHS);
9717 }
9718
9719 // Unsigned comparison is the same as signed comparison when both the operands
9720 // are non-negative.
9721 if (CmpInst::isUnsigned(FoundPred) &&
9722 CmpInst::getSignedPredicate(FoundPred) == Pred &&
9723 isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS))
9724 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
9725
9726 // Check if we can make progress by sharpening ranges.
9727 if (FoundPred == ICmpInst::ICMP_NE &&
9728 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) {
9729
9730 const SCEVConstant *C = nullptr;
9731 const SCEV *V = nullptr;
9732
9733 if (isa<SCEVConstant>(FoundLHS)) {
9734 C = cast<SCEVConstant>(FoundLHS);
9735 V = FoundRHS;
9736 } else {
9737 C = cast<SCEVConstant>(FoundRHS);
9738 V = FoundLHS;
9739 }
9740
9741 // The guarding predicate tells us that C != V. If the known range
9742 // of V is [C, t), we can sharpen the range to [C + 1, t). The
9743 // range we consider has to correspond to same signedness as the
9744 // predicate we're interested in folding.
9745
9746 APInt Min = ICmpInst::isSigned(Pred) ?
9747 getSignedRangeMin(V) : getUnsignedRangeMin(V);
9748
9749 if (Min == C->getAPInt()) {
9750 // Given (V >= Min && V != Min) we conclude V >= (Min + 1).
9751 // This is true even if (Min + 1) wraps around -- in case of
9752 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)).
9753
9754 APInt SharperMin = Min + 1;
9755
9756 switch (Pred) {
9757 case ICmpInst::ICMP_SGE:
9758 case ICmpInst::ICMP_UGE:
9759 // We know V `Pred` SharperMin. If this implies LHS `Pred`
9760 // RHS, we're done.
9761 if (isImpliedCondOperands(Pred, LHS, RHS, V,
9762 getConstant(SharperMin)))
9763 return true;
9764 LLVM_FALLTHROUGH;
9765
9766 case ICmpInst::ICMP_SGT:
9767 case ICmpInst::ICMP_UGT:
9768 // We know from the range information that (V `Pred` Min ||
9769 // V == Min). We know from the guarding condition that !(V
9770 // == Min). This gives us
9771 //
9772 // V `Pred` Min || V == Min && !(V == Min)
9773 // => V `Pred` Min
9774 //
9775 // If V `Pred` Min implies LHS `Pred` RHS, we're done.
9776
9777 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min)))
9778 return true;
9779 LLVM_FALLTHROUGH;
9780
9781 default:
9782 // No change
9783 break;
9784 }
9785 }
9786 }
9787
9788 // Check whether the actual condition is beyond sufficient.
9789 if (FoundPred == ICmpInst::ICMP_EQ)
9790 if (ICmpInst::isTrueWhenEqual(Pred))
9791 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
9792 return true;
9793 if (Pred == ICmpInst::ICMP_NE)
9794 if (!ICmpInst::isTrueWhenEqual(FoundPred))
9795 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
9796 return true;
9797
9798 // Otherwise assume the worst.
9799 return false;
9800}
9801
9802bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr,
9803 const SCEV *&L, const SCEV *&R,
9804 SCEV::NoWrapFlags &Flags) {
9805 const auto *AE = dyn_cast<SCEVAddExpr>(Expr);
9806 if (!AE || AE->getNumOperands() != 2)
9807 return false;
9808
9809 L = AE->getOperand(0);
9810 R = AE->getOperand(1);
9811 Flags = AE->getNoWrapFlags();
9812 return true;
9813}
9814
9815Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More,
9816 const SCEV *Less) {
9817 // We avoid subtracting expressions here because this function is usually
9818 // fairly deep in the call stack (i.e. is called many times).
9819
9820 if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) {
9821 const auto *LAR = cast<SCEVAddRecExpr>(Less);
9822 const auto *MAR = cast<SCEVAddRecExpr>(More);
9823
9824 if (LAR->getLoop() != MAR->getLoop())
9825 return None;
9826
9827 // We look at affine expressions only; not for correctness but to keep
9828 // getStepRecurrence cheap.
9829 if (!LAR->isAffine() || !MAR->isAffine())
9830 return None;
9831
9832 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this))
9833 return None;
9834
9835 Less = LAR->getStart();
9836 More = MAR->getStart();
9837
9838 // fall through
9839 }
9840
9841 if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) {
9842 const auto &M = cast<SCEVConstant>(More)->getAPInt();
9843 const auto &L = cast<SCEVConstant>(Less)->getAPInt();
9844 return M - L;
9845 }
9846
9847 SCEV::NoWrapFlags Flags;
9848 const SCEV *LLess = nullptr, *RLess = nullptr;
9849 const SCEV *LMore = nullptr, *RMore = nullptr;
9850 const SCEVConstant *C1 = nullptr, *C2 = nullptr;
9851 // Compare (X + C1) vs X.
9852 if (splitBinaryAdd(Less, LLess, RLess, Flags))
9853 if ((C1 = dyn_cast<SCEVConstant>(LLess)))
9854 if (RLess == More)
9855 return -(C1->getAPInt());
9856
9857 // Compare X vs (X + C2).
9858 if (splitBinaryAdd(More, LMore, RMore, Flags))
9859 if ((C2 = dyn_cast<SCEVConstant>(LMore)))
9860 if (RMore == Less)
9861 return C2->getAPInt();
9862
9863 // Compare (X + C1) vs (X + C2).
9864 if (C1 && C2 && RLess == RMore)
9865 return C2->getAPInt() - C1->getAPInt();
9866
9867 return None;
9868}
9869
9870bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow(
9871 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
9872 const SCEV *FoundLHS, const SCEV *FoundRHS) {
9873 if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT)
9874 return false;
9875
9876 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS);
9877 if (!AddRecLHS)
9878 return false;
9879
9880 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS);
9881 if (!AddRecFoundLHS)
9882 return false;
9883
9884 // We'd like to let SCEV reason about control dependencies, so we constrain
9885 // both the inequalities to be about add recurrences on the same loop. This
9886 // way we can use isLoopEntryGuardedByCond later.
9887
9888 const Loop *L = AddRecFoundLHS->getLoop();
9889 if (L != AddRecLHS->getLoop())
9890 return false;
9891
9892 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1)
9893 //
9894 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C)
9895 // ... (2)
9896 //
9897 // Informal proof for (2), assuming (1) [*]:
9898 //
9899 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**]
9900 //
9901 // Then
9902 //
9903 // FoundLHS s< FoundRHS s< INT_MIN - C
9904 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ]
9905 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ]
9906 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s<
9907 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ]
9908 // <=> FoundLHS + C s< FoundRHS + C
9909 //
9910 // [*]: (1) can be proved by ruling out overflow.
9911 //
9912 // [**]: This can be proved by analyzing all the four possibilities:
9913 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and
9914 // (A s>= 0, B s>= 0).
9915 //
9916 // Note:
9917 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C"
9918 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS
9919 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS
9920 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is
9921 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS +
9922 // C)".
9923
9924 Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS);
9925 Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS);
9926 if (!LDiff || !RDiff || *LDiff != *RDiff)
9927 return false;
9928
9929 if (LDiff->isMinValue())
9930 return true;
9931
9932 APInt FoundRHSLimit;
9933
9934 if (Pred == CmpInst::ICMP_ULT) {
9935 FoundRHSLimit = -(*RDiff);
9936 } else {
9937 assert(Pred == CmpInst::ICMP_SLT && "Checked above!");
9938 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff;
9939 }
9940
9941 // Try to prove (1) or (2), as needed.
9942 return isAvailableAtLoopEntry(FoundRHS, L) &&
9943 isLoopEntryGuardedByCond(L, Pred, FoundRHS,
9944 getConstant(FoundRHSLimit));
9945}
9946
9947bool ScalarEvolution::isImpliedViaMerge(ICmpInst::Predicate Pred,
9948 const SCEV *LHS, const SCEV *RHS,
9949 const SCEV *FoundLHS,
9950 const SCEV *FoundRHS, unsigned Depth) {
9951 const PHINode *LPhi = nullptr, *RPhi = nullptr;
9952
9953 auto ClearOnExit = make_scope_exit([&]() {
9954 if (LPhi) {
9955 bool Erased = PendingMerges.erase(LPhi);
9956 assert(Erased && "Failed to erase LPhi!");
9957 (void)Erased;
9958 }
9959 if (RPhi) {
9960 bool Erased = PendingMerges.erase(RPhi);
9961 assert(Erased && "Failed to erase RPhi!");
9962 (void)Erased;
9963 }
9964 });
9965
9966 // Find respective Phis and check that they are not being pending.
9967 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS))
9968 if (auto *Phi = dyn_cast<PHINode>(LU->getValue())) {
9969 if (!PendingMerges.insert(Phi).second)
9970 return false;
9971 LPhi = Phi;
9972 }
9973 if (const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS))
9974 if (auto *Phi = dyn_cast<PHINode>(RU->getValue())) {
9975 // If we detect a loop of Phi nodes being processed by this method, for
9976 // example:
9977 //
9978 // %a = phi i32 [ %some1, %preheader ], [ %b, %latch ]
9979 // %b = phi i32 [ %some2, %preheader ], [ %a, %latch ]
9980 //
9981 // we don't want to deal with a case that complex, so return conservative
9982 // answer false.
9983 if (!PendingMerges.insert(Phi).second)
9984 return false;
9985 RPhi = Phi;
9986 }
9987
9988 // If none of LHS, RHS is a Phi, nothing to do here.
9989 if (!LPhi && !RPhi)
9990 return false;
9991
9992 // If there is a SCEVUnknown Phi we are interested in, make it left.
9993 if (!LPhi) {
9994 std::swap(LHS, RHS);
9995 std::swap(FoundLHS, FoundRHS);
9996 std::swap(LPhi, RPhi);
9997 Pred = ICmpInst::getSwappedPredicate(Pred);
9998 }
9999
10000 assert(LPhi && "LPhi should definitely be a SCEVUnknown Phi!");
10001 const BasicBlock *LBB = LPhi->getParent();
10002 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
10003
10004 auto ProvedEasily = [&](const SCEV *S1, const SCEV *S2) {
10005 return isKnownViaNonRecursiveReasoning(Pred, S1, S2) ||
10006 isImpliedCondOperandsViaRanges(Pred, S1, S2, FoundLHS, FoundRHS) ||
10007 isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth);
10008 };
10009
10010 if (RPhi && RPhi->getParent() == LBB) {
10011 // Case one: RHS is also a SCEVUnknown Phi from the same basic block.
10012 // If we compare two Phis from the same block, and for each entry block
10013 // the predicate is true for incoming values from this block, then the
10014 // predicate is also true for the Phis.
10015 for (const BasicBlock *IncBB : predecessors(LBB)) {
10016 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
10017 const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB));
10018 if (!ProvedEasily(L, R))
10019 return false;
10020 }
10021 } else if (RAR && RAR->getLoop()->getHeader() == LBB) {
10022 // Case two: RHS is also a Phi from the same basic block, and it is an
10023 // AddRec. It means that there is a loop which has both AddRec and Unknown
10024 // PHIs, for it we can compare incoming values of AddRec from above the loop
10025 // and latch with their respective incoming values of LPhi.
10026 // TODO: Generalize to handle loops with many inputs in a header.
10027 if (LPhi->getNumIncomingValues() != 2) return false;
10028
10029 auto *RLoop = RAR->getLoop();
10030 auto *Predecessor = RLoop->getLoopPredecessor();
10031 assert(Predecessor && "Loop with AddRec with no predecessor?");
10032 const SCEV *L1 = getSCEV(LPhi->getIncomingValueForBlock(Predecessor));
10033 if (!ProvedEasily(L1, RAR->getStart()))
10034 return false;
10035 auto *Latch = RLoop->getLoopLatch();
10036 assert(Latch && "Loop with AddRec with no latch?");
10037 const SCEV *L2 = getSCEV(LPhi->getIncomingValueForBlock(Latch));
10038 if (!ProvedEasily(L2, RAR->getPostIncExpr(*this)))
10039 return false;
10040 } else {
10041 // In all other cases go over inputs of LHS and compare each of them to RHS,
10042 // the predicate is true for (LHS, RHS) if it is true for all such pairs.
10043 // At this point RHS is either a non-Phi, or it is a Phi from some block
10044 // different from LBB.
10045 for (const BasicBlock *IncBB : predecessors(LBB)) {
10046 // Check that RHS is available in this block.
10047 if (!dominates(RHS, IncBB))
10048 return false;
10049 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
10050 if (!ProvedEasily(L, RHS))
10051 return false;
10052 }
10053 }
10054 return true;
10055}
10056
10057bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
10058 const SCEV *LHS, const SCEV *RHS,
10059 const SCEV *FoundLHS,
10060 const SCEV *FoundRHS) {
10061 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS))
10062 return true;
10063
10064 if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS))
10065 return true;
10066
10067 return isImpliedCondOperandsHelper(Pred, LHS, RHS,
10068 FoundLHS, FoundRHS) ||
10069 // ~x < ~y --> x > y
10070 isImpliedCondOperandsHelper(Pred, LHS, RHS,
10071 getNotSCEV(FoundRHS),
10072 getNotSCEV(FoundLHS));
10073}
10074
10075/// Is MaybeMinMaxExpr an (U|S)(Min|Max) of Candidate and some other values?
10076template <typename MinMaxExprType>
10077static bool IsMinMaxConsistingOf(const SCEV *MaybeMinMaxExpr,
10078 const SCEV *Candidate) {
10079 const MinMaxExprType *MinMaxExpr = dyn_cast<MinMaxExprType>(MaybeMinMaxExpr);
10080 if (!MinMaxExpr)
10081 return false;
10082
10083 return find(MinMaxExpr->operands(), Candidate) != MinMaxExpr->op_end();
10084}
10085
10086static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE,
10087 ICmpInst::Predicate Pred,
10088 const SCEV *LHS, const SCEV *RHS) {
10089 // If both sides are affine addrecs for the same loop, with equal
10090 // steps, and we know the recurrences don't wrap, then we only
10091 // need to check the predicate on the starting values.
10092
10093 if (!ICmpInst::isRelational(Pred))
10094 return false;
10095
10096 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
10097 if (!LAR)
10098 return false;
10099 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
10100 if (!RAR)
10101 return false;
10102 if (LAR->getLoop() != RAR->getLoop())
10103 return false;
10104 if (!LAR->isAffine() || !RAR->isAffine())
10105 return false;
10106
10107 if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE))
10108 return false;
10109
10110 SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ?
10111 SCEV::FlagNSW : SCEV::FlagNUW;
10112 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW))
10113 return false;
10114
10115 return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart());
10116}
10117
10118/// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max
10119/// expression?
10120static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE,
10121 ICmpInst::Predicate Pred,
10122 const SCEV *LHS, const SCEV *RHS) {
10123 switch (Pred) {
10124 default:
10125 return false;
10126
10127 case ICmpInst::ICMP_SGE:
10128 std::swap(LHS, RHS);
10129 LLVM_FALLTHROUGH;
10130 case ICmpInst::ICMP_SLE:
10131 return
10132 // min(A, ...) <= A
10133 IsMinMaxConsistingOf<SCEVSMinExpr>(LHS, RHS) ||
10134 // A <= max(A, ...)
10135 IsMinMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS);
10136
10137 case ICmpInst::ICMP_UGE:
10138 std::swap(LHS, RHS);
10139 LLVM_FALLTHROUGH;
10140 case ICmpInst::ICMP_ULE:
10141 return
10142 // min(A, ...) <= A
10143 IsMinMaxConsistingOf<SCEVUMinExpr>(LHS, RHS) ||
10144 // A <= max(A, ...)
10145 IsMinMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS);
10146 }
10147
10148 llvm_unreachable("covered switch fell through?!");
10149}
10150
10151bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred,
10152 const SCEV *LHS, const SCEV *RHS,
10153 const SCEV *FoundLHS,
10154 const SCEV *FoundRHS,
10155 unsigned Depth) {
10156 assert(getTypeSizeInBits(LHS->getType()) ==
10157 getTypeSizeInBits(RHS->getType()) &&
10158 "LHS and RHS have different sizes?");
10159 assert(getTypeSizeInBits(FoundLHS->getType()) ==
10160 getTypeSizeInBits(FoundRHS->getType()) &&
10161 "FoundLHS and FoundRHS have different sizes?");
10162 // We want to avoid hurting the compile time with analysis of too big trees.
10163 if (Depth > MaxSCEVOperationsImplicationDepth)
10164 return false;
10165 // We only want to work with ICMP_SGT comparison so far.
10166 // TODO: Extend to ICMP_UGT?
10167 if (Pred == ICmpInst::ICMP_SLT) {
10168 Pred = ICmpInst::ICMP_SGT;
10169 std::swap(LHS, RHS);
10170 std::swap(FoundLHS, FoundRHS);
10171 }
10172 if (Pred != ICmpInst::ICMP_SGT)
10173 return false;
10174
10175 auto GetOpFromSExt = [&](const SCEV *S) {
10176 if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S))
10177 return Ext->getOperand();
10178 // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off
10179 // the constant in some cases.
10180 return S;
10181 };
10182
10183 // Acquire values from extensions.
10184 auto *OrigLHS = LHS;
10185 auto *OrigFoundLHS = FoundLHS;
10186 LHS = GetOpFromSExt(LHS);
10187 FoundLHS = GetOpFromSExt(FoundLHS);
10188
10189 // Is the SGT predicate can be proved trivially or using the found context.
10190 auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) {
10191 return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) ||
10192 isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS,
10193 FoundRHS, Depth + 1);
10194 };
10195
10196 if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) {
10197 // We want to avoid creation of any new non-constant SCEV. Since we are
10198 // going to compare the operands to RHS, we should be certain that we don't
10199 // need any size extensions for this. So let's decline all cases when the
10200 // sizes of types of LHS and RHS do not match.
10201 // TODO: Maybe try to get RHS from sext to catch more cases?
10202 if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType()))
10203 return false;
10204
10205 // Should not overflow.
10206 if (!LHSAddExpr->hasNoSignedWrap())
10207 return false;
10208
10209 auto *LL = LHSAddExpr->getOperand(0);
10210 auto *LR = LHSAddExpr->getOperand(1);
10211 auto *MinusOne = getNegativeSCEV(getOne(RHS->getType()));
10212
10213 // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context.
10214 auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) {
10215 return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS);
10216 };
10217 // Try to prove the following rule:
10218 // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS).
10219 // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS).
10220 if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL))
10221 return true;
10222 } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) {
10223 Value *LL, *LR;
10224 // FIXME: Once we have SDiv implemented, we can get rid of this matching.
10225
10226 using namespace llvm::PatternMatch;
10227
10228 if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) {
10229 // Rules for division.
10230 // We are going to perform some comparisons with Denominator and its
10231 // derivative expressions. In general case, creating a SCEV for it may
10232 // lead to a complex analysis of the entire graph, and in particular it
10233 // can request trip count recalculation for the same loop. This would
10234 // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid
10235 // this, we only want to create SCEVs that are constants in this section.
10236 // So we bail if Denominator is not a constant.
10237 if (!isa<ConstantInt>(LR))
10238 return false;
10239
10240 auto *Denominator = cast<SCEVConstant>(getSCEV(LR));
10241
10242 // We want to make sure that LHS = FoundLHS / Denominator. If it is so,
10243 // then a SCEV for the numerator already exists and matches with FoundLHS.
10244 auto *Numerator = getExistingSCEV(LL);
10245 if (!Numerator || Numerator->getType() != FoundLHS->getType())
10246 return false;
10247
10248 // Make sure that the numerator matches with FoundLHS and the denominator
10249 // is positive.
10250 if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator))
10251 return false;
10252
10253 auto *DTy = Denominator->getType();
10254 auto *FRHSTy = FoundRHS->getType();
10255 if (DTy->isPointerTy() != FRHSTy->isPointerTy())
10256 // One of types is a pointer and another one is not. We cannot extend
10257 // them properly to a wider type, so let us just reject this case.
10258 // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help
10259 // to avoid this check.
10260 return false;
10261
10262 // Given that:
10263 // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0.
10264 auto *WTy = getWiderType(DTy, FRHSTy);
10265 auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy);
10266 auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy);
10267
10268 // Try to prove the following rule:
10269 // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS).
10270 // For example, given that FoundLHS > 2. It means that FoundLHS is at
10271 // least 3. If we divide it by Denominator < 4, we will have at least 1.
10272 auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2));
10273 if (isKnownNonPositive(RHS) &&
10274 IsSGTViaContext(FoundRHSExt, DenomMinusTwo))
10275 return true;
10276
10277 // Try to prove the following rule:
10278 // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS).
10279 // For example, given that FoundLHS > -3. Then FoundLHS is at least -2.
10280 // If we divide it by Denominator > 2, then:
10281 // 1. If FoundLHS is negative, then the result is 0.
10282 // 2. If FoundLHS is non-negative, then the result is non-negative.
10283 // Anyways, the result is non-negative.
10284 auto *MinusOne = getNegativeSCEV(getOne(WTy));
10285 auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt);
10286 if (isKnownNegative(RHS) &&
10287 IsSGTViaContext(FoundRHSExt, NegDenomMinusOne))
10288 return true;
10289 }
10290 }
10291
10292 // If our expression contained SCEVUnknown Phis, and we split it down and now
10293 // need to prove something for them, try to prove the predicate for every
10294 // possible incoming values of those Phis.
10295 if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS, Depth + 1))
10296 return true;
10297
10298 return false;
10299}
10300
10301bool
10302ScalarEvolution::isKnownViaNonRecursiveReasoning(ICmpInst::Predicate Pred,
10303 const SCEV *LHS, const SCEV *RHS) {
10304 return isKnownPredicateViaConstantRanges(Pred, LHS, RHS) ||
10305 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) ||
10306 IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) ||
10307 isKnownPredicateViaNoOverflow(Pred, LHS, RHS);
10308}
10309
10310bool
10311ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
10312 const SCEV *LHS, const SCEV *RHS,
10313 const SCEV *FoundLHS,
10314 const SCEV *FoundRHS) {
10315 switch (Pred) {
10316 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
10317 case ICmpInst::ICMP_EQ:
10318 case ICmpInst::ICMP_NE:
10319 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
10320 return true;
10321 break;
10322 case ICmpInst::ICMP_SLT:
10323 case ICmpInst::ICMP_SLE:
10324 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
10325 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS))
10326 return true;
10327 break;
10328 case ICmpInst::ICMP_SGT:
10329 case ICmpInst::ICMP_SGE:
10330 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
10331 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS))
10332 return true;
10333 break;
10334 case ICmpInst::ICMP_ULT:
10335 case ICmpInst::ICMP_ULE:
10336 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
10337 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS))
10338 return true;
10339 break;
10340 case ICmpInst::ICMP_UGT:
10341 case ICmpInst::ICMP_UGE:
10342 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
10343 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS))
10344 return true;
10345 break;
10346 }
10347
10348 // Maybe it can be proved via operations?
10349 if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS))
10350 return true;
10351
10352 return false;
10353}
10354
10355bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred,
10356 const SCEV *LHS,
10357 const SCEV *RHS,
10358 const SCEV *FoundLHS,
10359 const SCEV *FoundRHS) {
10360 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS))
10361 // The restriction on `FoundRHS` be lifted easily -- it exists only to
10362 // reduce the compile time impact of this optimization.
10363 return false;
10364
10365 Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS);
10366 if (!Addend)
10367 return false;
10368
10369 const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt();
10370
10371 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the
10372 // antecedent "`FoundLHS` `Pred` `FoundRHS`".
10373 ConstantRange FoundLHSRange =
10374 ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS);
10375
10376 // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`:
10377 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend));
10378
10379 // We can also compute the range of values for `LHS` that satisfy the
10380 // consequent, "`LHS` `Pred` `RHS`":
10381 const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt();
10382 ConstantRange SatisfyingLHSRange =
10383 ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS);
10384
10385 // The antecedent implies the consequent if every value of `LHS` that
10386 // satisfies the antecedent also satisfies the consequent.
10387 return SatisfyingLHSRange.contains(LHSRange);
10388}
10389
10390bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
10391 bool IsSigned, bool NoWrap) {
10392 assert(isKnownPositive(Stride) && "Positive stride expected!");
10393
10394 if (NoWrap) return false;
10395
10396 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
10397 const SCEV *One = getOne(Stride->getType());
10398
10399 if (IsSigned) {
10400 APInt MaxRHS = getSignedRangeMax(RHS);
10401 APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
10402 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
10403
10404 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow!
10405 return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS);
10406 }
10407
10408 APInt MaxRHS = getUnsignedRangeMax(RHS);
10409 APInt MaxValue = APInt::getMaxValue(BitWidth);
10410 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
10411
10412 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow!
10413 return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS);
10414}
10415
10416bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride,
10417 bool IsSigned, bool NoWrap) {
10418 if (NoWrap) return false;
10419
10420 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
10421 const SCEV *One = getOne(Stride->getType());
10422
10423 if (IsSigned) {
10424 APInt MinRHS = getSignedRangeMin(RHS);
10425 APInt MinValue = APInt::getSignedMinValue(BitWidth);
10426 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
10427
10428 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow!
10429 return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS);
10430 }
10431
10432 APInt MinRHS = getUnsignedRangeMin(RHS);
10433 APInt MinValue = APInt::getMinValue(BitWidth);
10434 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
10435
10436 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow!
10437 return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS);
10438}
10439
10440const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step,
10441 bool Equality) {
10442 const SCEV *One = getOne(Step->getType());
10443 Delta = Equality ? getAddExpr(Delta, Step)
10444 : getAddExpr(Delta, getMinusSCEV(Step, One));
10445 return getUDivExpr(Delta, Step);
10446}
10447
10448const SCEV *ScalarEvolution::computeMaxBECountForLT(const SCEV *Start,
10449 const SCEV *Stride,
10450 const SCEV *End,
10451 unsigned BitWidth,
10452 bool IsSigned) {
10453
10454 assert(!isKnownNonPositive(Stride) &&
10455 "Stride is expected strictly positive!");
10456 // Calculate the maximum backedge count based on the range of values
10457 // permitted by Start, End, and Stride.
10458 const SCEV *MaxBECount;
10459 APInt MinStart =
10460 IsSigned ? getSignedRangeMin(Start) : getUnsignedRangeMin(Start);
10461
10462 APInt StrideForMaxBECount =
10463 IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride);
10464
10465 // We already know that the stride is positive, so we paper over conservatism
10466 // in our range computation by forcing StrideForMaxBECount to be at least one.
10467 // In theory this is unnecessary, but we expect MaxBECount to be a
10468 // SCEVConstant, and (udiv <constant> 0) is not constant folded by SCEV (there
10469 // is nothing to constant fold it to).
10470 APInt One(BitWidth, 1, IsSigned);
10471 StrideForMaxBECount = APIntOps::smax(One, StrideForMaxBECount);
10472
10473 APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth)
10474 : APInt::getMaxValue(BitWidth);
10475 APInt Limit = MaxValue - (StrideForMaxBECount - 1);
10476
10477 // Although End can be a MAX expression we estimate MaxEnd considering only
10478 // the case End = RHS of the loop termination condition. This is safe because
10479 // in the other case (End - Start) is zero, leading to a zero maximum backedge
10480 // taken count.
10481 APInt MaxEnd = IsSigned ? APIntOps::smin(getSignedRangeMax(End), Limit)
10482 : APIntOps::umin(getUnsignedRangeMax(End), Limit);
10483
10484 MaxBECount = computeBECount(getConstant(MaxEnd - MinStart) /* Delta */,
10485 getConstant(StrideForMaxBECount) /* Step */,
10486 false /* Equality */);
10487
10488 return MaxBECount;
10489}
10490
10491ScalarEvolution::ExitLimit
10492ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS,
10493 const Loop *L, bool IsSigned,
10494 bool ControlsExit, bool AllowPredicates) {
10495 SmallPtrSet<const SCEVPredicate *, 4> Predicates;
10496
10497 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
10498 bool PredicatedIV = false;
10499
10500 if (!IV && AllowPredicates) {
10501 // Try to make this an AddRec using runtime tests, in the first X
10502 // iterations of this loop, where X is the SCEV expression found by the
10503 // algorithm below.
10504 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
10505 PredicatedIV = true;
10506 }
10507
10508 // Avoid weird loops
10509 if (!IV || IV->getLoop() != L || !IV->isAffine())
10510 return getCouldNotCompute();
10511
10512 bool NoWrap = ControlsExit &&
10513 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
10514
10515 const SCEV *Stride = IV->getStepRecurrence(*this);
10516
10517 bool PositiveStride = isKnownPositive(Stride);
10518
10519 // Avoid negative or zero stride values.
10520 if (!PositiveStride) {
10521 // We can compute the correct backedge taken count for loops with unknown
10522 // strides if we can prove that the loop is not an infinite loop with side
10523 // effects. Here's the loop structure we are trying to handle -
10524 //
10525 // i = start
10526 // do {
10527 // A[i] = i;
10528 // i += s;
10529 // } while (i < end);
10530 //
10531 // The backedge taken count for such loops is evaluated as -
10532 // (max(end, start + stride) - start - 1) /u stride
10533 //
10534 // The additional preconditions that we need to check to prove correctness
10535 // of the above formula is as follows -
10536 //
10537 // a) IV is either nuw or nsw depending upon signedness (indicated by the
10538 // NoWrap flag).
10539 // b) loop is single exit with no side effects.
10540 //
10541 //
10542 // Precondition a) implies that if the stride is negative, this is a single
10543 // trip loop. The backedge taken count formula reduces to zero in this case.
10544 //
10545 // Precondition b) implies that the unknown stride cannot be zero otherwise
10546 // we have UB.
10547 //
10548 // The positive stride case is the same as isKnownPositive(Stride) returning
10549 // true (original behavior of the function).
10550 //
10551 // We want to make sure that the stride is truly unknown as there are edge
10552 // cases where ScalarEvolution propagates no wrap flags to the
10553 // post-increment/decrement IV even though the increment/decrement operation
10554 // itself is wrapping. The computed backedge taken count may be wrong in
10555 // such cases. This is prevented by checking that the stride is not known to
10556 // be either positive or non-positive. For example, no wrap flags are
10557 // propagated to the post-increment IV of this loop with a trip count of 2 -
10558 //
10559 // unsigned char i;
10560 // for(i=127; i<128; i+=129)
10561 // A[i] = i;
10562 //
10563 if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) ||
10564 !loopHasNoSideEffects(L))
10565 return getCouldNotCompute();
10566 } else if (!Stride->isOne() &&
10567 doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap))
10568 // Avoid proven overflow cases: this will ensure that the backedge taken
10569 // count will not generate any unsigned overflow. Relaxed no-overflow
10570 // conditions exploit NoWrapFlags, allowing to optimize in presence of
10571 // undefined behaviors like the case of C language.
10572 return getCouldNotCompute();
10573
10574 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT
10575 : ICmpInst::ICMP_ULT;
10576 const SCEV *Start = IV->getStart();
10577 const SCEV *End = RHS;
10578 // When the RHS is not invariant, we do not know the end bound of the loop and
10579 // cannot calculate the ExactBECount needed by ExitLimit. However, we can
10580 // calculate the MaxBECount, given the start, stride and max value for the end
10581 // bound of the loop (RHS), and the fact that IV does not overflow (which is
10582 // checked above).
10583 if (!isLoopInvariant(RHS, L)) {
10584 const SCEV *MaxBECount = computeMaxBECountForLT(
10585 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned);
10586 return ExitLimit(getCouldNotCompute() /* ExactNotTaken */, MaxBECount,
10587 false /*MaxOrZero*/, Predicates);
10588 }
10589 // If the backedge is taken at least once, then it will be taken
10590 // (End-Start)/Stride times (rounded up to a multiple of Stride), where Start
10591 // is the LHS value of the less-than comparison the first time it is evaluated
10592 // and End is the RHS.
10593 const SCEV *BECountIfBackedgeTaken =
10594 computeBECount(getMinusSCEV(End, Start), Stride, false);
10595 // If the loop entry is guarded by the result of the backedge test of the
10596 // first loop iteration, then we know the backedge will be taken at least
10597 // once and so the backedge taken count is as above. If not then we use the
10598 // expression (max(End,Start)-Start)/Stride to describe the backedge count,
10599 // as if the backedge is taken at least once max(End,Start) is End and so the
10600 // result is as above, and if not max(End,Start) is Start so we get a backedge
10601 // count of zero.
10602 const SCEV *BECount;
10603 if (isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS))
10604 BECount = BECountIfBackedgeTaken;
10605 else {
10606 End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start);
10607 BECount = computeBECount(getMinusSCEV(End, Start), Stride, false);
10608 }
10609
10610 const SCEV *MaxBECount;
10611 bool MaxOrZero = false;
10612 if (isa<SCEVConstant>(BECount))
10613 MaxBECount = BECount;
10614 else if (isa<SCEVConstant>(BECountIfBackedgeTaken)) {
10615 // If we know exactly how many times the backedge will be taken if it's
10616 // taken at least once, then the backedge count will either be that or
10617 // zero.
10618 MaxBECount = BECountIfBackedgeTaken;
10619 MaxOrZero = true;
10620 } else {
10621 MaxBECount = computeMaxBECountForLT(
10622 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned);
10623 }
10624
10625 if (isa<SCEVCouldNotCompute>(MaxBECount) &&
10626 !isa<SCEVCouldNotCompute>(BECount))
10627 MaxBECount = getConstant(getUnsignedRangeMax(BECount));
10628
10629 return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates);
10630}
10631
10632ScalarEvolution::ExitLimit
10633ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS,
10634 const Loop *L, bool IsSigned,
10635 bool ControlsExit, bool AllowPredicates) {
10636 SmallPtrSet<const SCEVPredicate *, 4> Predicates;
10637 // We handle only IV > Invariant
10638 if (!isLoopInvariant(RHS, L))
10639 return getCouldNotCompute();
10640
10641 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
10642 if (!IV && AllowPredicates)
10643 // Try to make this an AddRec using runtime tests, in the first X
10644 // iterations of this loop, where X is the SCEV expression found by the
10645 // algorithm below.
10646 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
10647
10648 // Avoid weird loops
10649 if (!IV || IV->getLoop() != L || !IV->isAffine())
10650 return getCouldNotCompute();
10651
10652 bool NoWrap = ControlsExit &&
10653 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
10654
10655 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this));
10656
10657 // Avoid negative or zero stride values
10658 if (!isKnownPositive(Stride))
10659 return getCouldNotCompute();
10660
10661 // Avoid proven overflow cases: this will ensure that the backedge taken count
10662 // will not generate any unsigned overflow. Relaxed no-overflow conditions
10663 // exploit NoWrapFlags, allowing to optimize in presence of undefined
10664 // behaviors like the case of C language.
10665 if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap))
10666 return getCouldNotCompute();
10667
10668 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT
10669 : ICmpInst::ICMP_UGT;
10670
10671 const SCEV *Start = IV->getStart();
10672 const SCEV *End = RHS;
10673 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS))
10674 End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start);
10675
10676 const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false);
10677
10678 APInt MaxStart = IsSigned ? getSignedRangeMax(Start)
10679 : getUnsignedRangeMax(Start);
10680
10681 APInt MinStride = IsSigned ? getSignedRangeMin(Stride)
10682 : getUnsignedRangeMin(Stride);
10683
10684 unsigned BitWidth = getTypeSizeInBits(LHS->getType());
10685 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1)
10686 : APInt::getMinValue(BitWidth) + (MinStride - 1);
10687
10688 // Although End can be a MIN expression we estimate MinEnd considering only
10689 // the case End = RHS. This is safe because in the other case (Start - End)
10690 // is zero, leading to a zero maximum backedge taken count.
10691 APInt MinEnd =
10692 IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit)
10693 : APIntOps::umax(getUnsignedRangeMin(RHS), Limit);
10694
10695
10696 const SCEV *MaxBECount = getCouldNotCompute();
10697 if (isa<SCEVConstant>(BECount))
10698 MaxBECount = BECount;
10699 else
10700 MaxBECount = computeBECount(getConstant(MaxStart - MinEnd),
10701 getConstant(MinStride), false);
10702
10703 if (isa<SCEVCouldNotCompute>(MaxBECount))
10704 MaxBECount = BECount;
10705
10706 return ExitLimit(BECount, MaxBECount, false, Predicates);
10707}
10708
10709const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range,
10710 ScalarEvolution &SE) const {
10711 if (Range.isFullSet()) // Infinite loop.
10712 return SE.getCouldNotCompute();
10713
10714 // If the start is a non-zero constant, shift the range to simplify things.
10715 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
10716 if (!SC->getValue()->isZero()) {
10717 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
10718 Operands[0] = SE.getZero(SC->getType());
10719 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
10720 getNoWrapFlags(FlagNW));
10721 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
10722 return ShiftedAddRec->getNumIterationsInRange(
10723 Range.subtract(SC->getAPInt()), SE);
10724 // This is strange and shouldn't happen.
10725 return SE.getCouldNotCompute();
10726 }
10727
10728 // The only time we can solve this is when we have all constant indices.
10729 // Otherwise, we cannot determine the overflow conditions.
10730 if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); }))
10731 return SE.getCouldNotCompute();
10732
10733 // Okay at this point we know that all elements of the chrec are constants and
10734 // that the start element is zero.
10735
10736 // First check to see if the range contains zero. If not, the first
10737 // iteration exits.
10738 unsigned BitWidth = SE.getTypeSizeInBits(getType());
10739 if (!Range.contains(APInt(BitWidth, 0)))
10740 return SE.getZero(getType());
10741
10742 if (isAffine()) {
10743 // If this is an affine expression then we have this situation:
10744 // Solve {0,+,A} in Range === Ax in Range
10745
10746 // We know that zero is in the range. If A is positive then we know that
10747 // the upper value of the range must be the first possible exit value.
10748 // If A is negative then the lower of the range is the last possible loop
10749 // value. Also note that we already checked for a full range.
10750 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt();
10751 APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower();
10752
10753 // The exit value should be (End+A)/A.
10754 APInt ExitVal = (End + A).udiv(A);
10755 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
10756
10757 // Evaluate at the exit value. If we really did fall out of the valid
10758 // range, then we computed our trip count, otherwise wrap around or other
10759 // things must have happened.
10760 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
10761 if (Range.contains(Val->getValue()))
10762 return SE.getCouldNotCompute(); // Something strange happened
10763
10764 // Ensure that the previous value is in the range. This is a sanity check.
10765 assert(Range.contains(
10766 EvaluateConstantChrecAtConstant(this,
10767 ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) &&
10768 "Linear scev computation is off in a bad way!");
10769 return SE.getConstant(ExitValue);
10770 }
10771
10772 if (isQuadratic()) {
10773 if (auto S = SolveQuadraticAddRecRange(this, Range, SE))
10774 return SE.getConstant(S.getValue());
10775 }
10776
10777 return SE.getCouldNotCompute();
10778}
10779
10780const SCEVAddRecExpr *
10781SCEVAddRecExpr::getPostIncExpr(ScalarEvolution &SE) const {
10782 assert(getNumOperands() > 1 && "AddRec with zero step?");
10783 // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)),
10784 // but in this case we cannot guarantee that the value returned will be an
10785 // AddRec because SCEV does not have a fixed point where it stops
10786 // simplification: it is legal to return ({rec1} + {rec2}). For example, it
10787 // may happen if we reach arithmetic depth limit while simplifying. So we
10788 // construct the returned value explicitly.
10789 SmallVector<const SCEV *, 3> Ops;
10790 // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and
10791 // (this + Step) is {A+B,+,B+C,+...,+,N}.
10792 for (unsigned i = 0, e = getNumOperands() - 1; i < e; ++i)
10793 Ops.push_back(SE.getAddExpr(getOperand(i), getOperand(i + 1)));
10794 // We know that the last operand is not a constant zero (otherwise it would
10795 // have been popped out earlier). This guarantees us that if the result has
10796 // the same last operand, then it will also not be popped out, meaning that
10797 // the returned value will be an AddRec.
10798 const SCEV *Last = getOperand(getNumOperands() - 1);
10799 assert(!Last->isZero() && "Recurrency with zero step?");
10800 Ops.push_back(Last);
10801 return cast<SCEVAddRecExpr>(SE.getAddRecExpr(Ops, getLoop(),
10802 SCEV::FlagAnyWrap));
10803}
10804
10805// Return true when S contains at least an undef value.
10806static inline bool containsUndefs(const SCEV *S) {
10807 return SCEVExprContains(S, [](const SCEV *S) {
10808 if (const auto *SU = dyn_cast<SCEVUnknown>(S))
10809 return isa<UndefValue>(SU->getValue());
10810 return false;
10811 });
10812}
10813
10814namespace {
10815
10816// Collect all steps of SCEV expressions.
10817struct SCEVCollectStrides {
10818 ScalarEvolution &SE;
10819 SmallVectorImpl<const SCEV *> &Strides;
10820
10821 SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S)
10822 : SE(SE), Strides(S) {}
10823
10824 bool follow(const SCEV *S) {
10825 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
10826 Strides.push_back(AR->getStepRecurrence(SE));
10827 return true;
10828 }
10829
10830 bool isDone() const { return false; }
10831};
10832
10833// Collect all SCEVUnknown and SCEVMulExpr expressions.
10834struct SCEVCollectTerms {
10835 SmallVectorImpl<const SCEV *> &Terms;
10836
10837 SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T) : Terms(T) {}
10838
10839 bool follow(const SCEV *S) {
10840 if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S) ||
10841 isa<SCEVSignExtendExpr>(S)) {
10842 if (!containsUndefs(S))
10843 Terms.push_back(S);
10844
10845 // Stop recursion: once we collected a term, do not walk its operands.
10846 return false;
10847 }
10848
10849 // Keep looking.
10850 return true;
10851 }
10852
10853 bool isDone() const { return false; }
10854};
10855
10856// Check if a SCEV contains an AddRecExpr.
10857struct SCEVHasAddRec {
10858 bool &ContainsAddRec;
10859
10860 SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) {
10861 ContainsAddRec = false;
10862 }
10863
10864 bool follow(const SCEV *S) {
10865 if (isa<SCEVAddRecExpr>(S)) {
10866 ContainsAddRec = true;
10867
10868 // Stop recursion: once we collected a term, do not walk its operands.
10869 return false;
10870 }
10871
10872 // Keep looking.
10873 return true;
10874 }
10875
10876 bool isDone() const { return false; }
10877};
10878
10879// Find factors that are multiplied with an expression that (possibly as a
10880// subexpression) contains an AddRecExpr. In the expression:
10881//
10882// 8 * (100 + %p * %q * (%a + {0, +, 1}_loop))
10883//
10884// "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)"
10885// that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size
10886// parameters as they form a product with an induction variable.
10887//
10888// This collector expects all array size parameters to be in the same MulExpr.
10889// It might be necessary to later add support for collecting parameters that are
10890// spread over different nested MulExpr.
10891struct SCEVCollectAddRecMultiplies {
10892 SmallVectorImpl<const SCEV *> &Terms;
10893 ScalarEvolution &SE;
10894
10895 SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE)
10896 : Terms(T), SE(SE) {}
10897
10898 bool follow(const SCEV *S) {
10899 if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) {
10900 bool HasAddRec = false;
10901 SmallVector<const SCEV *, 0> Operands;
10902 for (auto Op : Mul->operands()) {
10903 const SCEVUnknown *Unknown = dyn_cast<SCEVUnknown>(Op);
10904 if (Unknown && !isa<CallInst>(Unknown->getValue())) {
10905 Operands.push_back(Op);
10906 } else if (Unknown) {
10907 HasAddRec = true;
10908 } else {
10909 bool ContainsAddRec;
10910 SCEVHasAddRec ContiansAddRec(ContainsAddRec);
10911 visitAll(Op, ContiansAddRec);
10912 HasAddRec |= ContainsAddRec;
10913 }
10914 }
10915 if (Operands.size() == 0)
10916 return true;
10917
10918 if (!HasAddRec)
10919 return false;
10920
10921 Terms.push_back(SE.getMulExpr(Operands));
10922 // Stop recursion: once we collected a term, do not walk its operands.
10923 return false;
10924 }
10925
10926 // Keep looking.
10927 return true;
10928 }
10929
10930 bool isDone() const { return false; }
10931};
10932
10933} // end anonymous namespace
10934
10935/// Find parametric terms in this SCEVAddRecExpr. We first for parameters in
10936/// two places:
10937/// 1) The strides of AddRec expressions.
10938/// 2) Unknowns that are multiplied with AddRec expressions.
10939void ScalarEvolution::collectParametricTerms(const SCEV *Expr,
10940 SmallVectorImpl<const SCEV *> &Terms) {
10941 SmallVector<const SCEV *, 4> Strides;
10942 SCEVCollectStrides StrideCollector(*this, Strides);
10943 visitAll(Expr, StrideCollector);
10944
10945 LLVM_DEBUG({
10946 dbgs() << "Strides:\n";
10947 for (const SCEV *S : Strides)
10948 dbgs() << *S << "\n";
10949 });
10950
10951 for (const SCEV *S : Strides) {
10952 SCEVCollectTerms TermCollector(Terms);
10953 visitAll(S, TermCollector);
10954 }
10955
10956 LLVM_DEBUG({
10957 dbgs() << "Terms:\n";
10958 for (const SCEV *T : Terms)
10959 dbgs() << *T << "\n";
10960 });
10961
10962 SCEVCollectAddRecMultiplies MulCollector(Terms, *this);
10963 visitAll(Expr, MulCollector);
10964}
10965
10966static bool findArrayDimensionsRec(ScalarEvolution &SE,
10967 SmallVectorImpl<const SCEV *> &Terms,
10968 SmallVectorImpl<const SCEV *> &Sizes) {
10969 int Last = Terms.size() - 1;
10970 const SCEV *Step = Terms[Last];
10971
10972 // End of recursion.
10973 if (Last == 0) {
10974 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) {
10975 SmallVector<const SCEV *, 2> Qs;
10976 for (const SCEV *Op : M->operands())
10977 if (!isa<SCEVConstant>(Op))
10978 Qs.push_back(Op);
10979
10980 Step = SE.getMulExpr(Qs);
10981 }
10982
10983 Sizes.push_back(Step);
10984 return true;
10985 }
10986
10987 for (const SCEV *&Term : Terms) {
10988 // Normalize the terms before the next call to findArrayDimensionsRec.
10989 const SCEV *Q, *R;
10990 SCEVDivision::divide(SE, Term, Step, &Q, &R);
10991
10992 // Bail out when GCD does not evenly divide one of the terms.
10993 if (!R->isZero())
10994 return false;
10995
10996 Term = Q;
10997 }
10998
10999 // Remove all SCEVConstants.
11000 Terms.erase(
11001 remove_if(Terms, [](const SCEV *E) { return isa<SCEVConstant>(E); }),
11002 Terms.end());
11003
11004 if (Terms.size() > 0)
11005 if (!findArrayDimensionsRec(SE, Terms, Sizes))
11006 return false;
11007
11008 Sizes.push_back(Step);
11009 return true;
11010}
11011
11012// Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter.
11013static inline bool containsParameters(SmallVectorImpl<const SCEV *> &Terms) {
11014 for (const SCEV *T : Terms)
11015 if (SCEVExprContains(T, isa<SCEVUnknown, const SCEV *>))
11016 return true;
11017 return false;
11018}
11019
11020// Return the number of product terms in S.
11021static inline int numberOfTerms(const SCEV *S) {
11022 if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S))
11023 return Expr->getNumOperands();
11024 return 1;
11025}
11026
11027static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) {
11028 if (isa<SCEVConstant>(T))
11029 return nullptr;
11030
11031 if (isa<SCEVUnknown>(T))
11032 return T;
11033
11034 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) {
11035 SmallVector<const SCEV *, 2> Factors;
11036 for (const SCEV *Op : M->operands())
11037 if (!isa<SCEVConstant>(Op))
11038 Factors.push_back(Op);
11039
11040 return SE.getMulExpr(Factors);
11041 }
11042
11043 return T;
11044}
11045
11046/// Return the size of an element read or written by Inst.
11047const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) {
11048 Type *Ty;
11049 if (StoreInst *Store = dyn_cast<StoreInst>(Inst))
11050 Ty = Store->getValueOperand()->getType();
11051 else if (LoadInst *Load = dyn_cast<LoadInst>(Inst))
11052 Ty = Load->getType();
11053 else
11054 return nullptr;
11055
11056 Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty));
11057 return getSizeOfExpr(ETy, Ty);
11058}
11059
11060void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms,
11061 SmallVectorImpl<const SCEV *> &Sizes,
11062 const SCEV *ElementSize) {
11063 if (Terms.size() < 1 || !ElementSize)
11064 return;
11065
11066 // Early return when Terms do not contain parameters: we do not delinearize
11067 // non parametric SCEVs.
11068 if (!containsParameters(Terms))
11069 return;
11070
11071 LLVM_DEBUG({
11072 dbgs() << "Terms:\n";
11073 for (const SCEV *T : Terms)
11074 dbgs() << *T << "\n";
11075 });
11076
11077 // Remove duplicates.
11078 array_pod_sort(Terms.begin(), Terms.end());
11079 Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end());
11080
11081 // Put larger terms first.
11082 llvm::sort(Terms, [](const SCEV *LHS, const SCEV *RHS) {
11083 return numberOfTerms(LHS) > numberOfTerms(RHS);
11084 });
11085
11086 // Try to divide all terms by the element size. If term is not divisible by
11087 // element size, proceed with the original term.
11088 for (const SCEV *&Term : Terms) {
11089 const SCEV *Q, *R;
11090 SCEVDivision::divide(*this, Term, ElementSize, &Q, &R);
11091 if (!Q->isZero())
11092 Term = Q;
11093 }
11094
11095 SmallVector<const SCEV *, 4> NewTerms;
11096
11097 // Remove constant factors.
11098 for (const SCEV *T : Terms)
11099 if (const SCEV *NewT = removeConstantFactors(*this, T))
11100 NewTerms.push_back(NewT);
11101
11102 LLVM_DEBUG({
11103 dbgs() << "Terms after sorting:\n";
11104 for (const SCEV *T : NewTerms)
11105 dbgs() << *T << "\n";
11106 });
11107
11108 if (NewTerms.empty() || !findArrayDimensionsRec(*this, NewTerms, Sizes)) {
11109 Sizes.clear();
11110 return;
11111 }
11112
11113 // The last element to be pushed into Sizes is the size of an element.
11114 Sizes.push_back(ElementSize);
11115
11116 LLVM_DEBUG({
11117 dbgs() << "Sizes:\n";
11118 for (const SCEV *S : Sizes)
11119 dbgs() << *S << "\n";
11120 });
11121}
11122
11123void ScalarEvolution::computeAccessFunctions(
11124 const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts,
11125 SmallVectorImpl<const SCEV *> &Sizes) {
11126 // Early exit in case this SCEV is not an affine multivariate function.
11127 if (Sizes.empty())
11128 return;
11129
11130 if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr))
11131 if (!AR->isAffine())
11132 return;
11133
11134 const SCEV *Res = Expr;
11135 int Last = Sizes.size() - 1;
11136 for (int i = Last; i >= 0; i--) {
11137 const SCEV *Q, *R;
11138 SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R);
11139
11140 LLVM_DEBUG({
11141 dbgs() << "Res: " << *Res << "\n";
11142 dbgs() << "Sizes[i]: " << *Sizes[i] << "\n";
11143 dbgs() << "Res divided by Sizes[i]:\n";
11144 dbgs() << "Quotient: " << *Q << "\n";
11145 dbgs() << "Remainder: " << *R << "\n";
11146 });
11147
11148 Res = Q;
11149
11150 // Do not record the last subscript corresponding to the size of elements in
11151 // the array.
11152 if (i == Last) {
11153
11154 // Bail out if the remainder is too complex.
11155 if (isa<SCEVAddRecExpr>(R)) {
11156 Subscripts.clear();
11157 Sizes.clear();
11158 return;
11159 }
11160
11161 continue;
11162 }
11163
11164 // Record the access function for the current subscript.
11165 Subscripts.push_back(R);
11166 }
11167
11168 // Also push in last position the remainder of the last division: it will be
11169 // the access function of the innermost dimension.
11170 Subscripts.push_back(Res);
11171
11172 std::reverse(Subscripts.begin(), Subscripts.end());
11173
11174 LLVM_DEBUG({
11175 dbgs() << "Subscripts:\n";
11176 for (const SCEV *S : Subscripts)
11177 dbgs() << *S << "\n";
11178 });
11179}
11180
11181/// Splits the SCEV into two vectors of SCEVs representing the subscripts and
11182/// sizes of an array access. Returns the remainder of the delinearization that
11183/// is the offset start of the array. The SCEV->delinearize algorithm computes
11184/// the multiples of SCEV coefficients: that is a pattern matching of sub
11185/// expressions in the stride and base of a SCEV corresponding to the
11186/// computation of a GCD (greatest common divisor) of base and stride. When
11187/// SCEV->delinearize fails, it returns the SCEV unchanged.
11188///
11189/// For example: when analyzing the memory access A[i][j][k] in this loop nest
11190///
11191/// void foo(long n, long m, long o, double A[n][m][o]) {
11192///
11193/// for (long i = 0; i < n; i++)
11194/// for (long j = 0; j < m; j++)
11195/// for (long k = 0; k < o; k++)
11196/// A[i][j][k] = 1.0;
11197/// }
11198///
11199/// the delinearization input is the following AddRec SCEV:
11200///
11201/// AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k>
11202///
11203/// From this SCEV, we are able to say that the base offset of the access is %A
11204/// because it appears as an offset that does not divide any of the strides in
11205/// the loops:
11206///
11207/// CHECK: Base offset: %A
11208///
11209/// and then SCEV->delinearize determines the size of some of the dimensions of
11210/// the array as these are the multiples by which the strides are happening:
11211///
11212/// CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes.
11213///
11214/// Note that the outermost dimension remains of UnknownSize because there are
11215/// no strides that would help identifying the size of the last dimension: when
11216/// the array has been statically allocated, one could compute the size of that
11217/// dimension by dividing the overall size of the array by the size of the known
11218/// dimensions: %m * %o * 8.
11219///
11220/// Finally delinearize provides the access functions for the array reference
11221/// that does correspond to A[i][j][k] of the above C testcase:
11222///
11223/// CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>]
11224///
11225/// The testcases are checking the output of a function pass:
11226/// DelinearizationPass that walks through all loads and stores of a function
11227/// asking for the SCEV of the memory access with respect to all enclosing
11228/// loops, calling SCEV->delinearize on that and printing the results.
11229void ScalarEvolution::delinearize(const SCEV *Expr,
11230 SmallVectorImpl<const SCEV *> &Subscripts,
11231 SmallVectorImpl<const SCEV *> &Sizes,
11232 const SCEV *ElementSize) {
11233 // First step: collect parametric terms.
11234 SmallVector<const SCEV *, 4> Terms;
11235 collectParametricTerms(Expr, Terms);
11236
11237 if (Terms.empty())
11238 return;
11239
11240 // Second step: find subscript sizes.
11241 findArrayDimensions(Terms, Sizes, ElementSize);
11242
11243 if (Sizes.empty())
11244 return;
11245
11246 // Third step: compute the access functions for each subscript.
11247 computeAccessFunctions(Expr, Subscripts, Sizes);
11248
11249 if (Subscripts.empty())
11250 return;
11251
11252 LLVM_DEBUG({
11253 dbgs() << "succeeded to delinearize " << *Expr << "\n";
11254 dbgs() << "ArrayDecl[UnknownSize]";
11255 for (const SCEV *S : Sizes)
11256 dbgs() << "[" << *S << "]";
11257
11258 dbgs() << "\nArrayRef";
11259 for (const SCEV *S : Subscripts)
11260 dbgs() << "[" << *S << "]";
11261 dbgs() << "\n";
11262 });
11263}
11264
11265//===----------------------------------------------------------------------===//
11266// SCEVCallbackVH Class Implementation
11267//===----------------------------------------------------------------------===//
11268
11269void ScalarEvolution::SCEVCallbackVH::deleted() {
11270 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
11271 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
11272 SE->ConstantEvolutionLoopExitValue.erase(PN);
11273 SE->eraseValueFromMap(getValPtr());
11274 // this now dangles!
11275}
11276
11277void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
11278 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
11279
11280 // Forget all the expressions associated with users of the old value,
11281 // so that future queries will recompute the expressions using the new
11282 // value.
11283 Value *Old = getValPtr();
11284 SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end());
11285 SmallPtrSet<User *, 8> Visited;
11286 while (!Worklist.empty()) {
11287 User *U = Worklist.pop_back_val();
11288 // Deleting the Old value will cause this to dangle. Postpone
11289 // that until everything else is done.
11290 if (U == Old)
11291 continue;
11292 if (!Visited.insert(U).second)
11293 continue;
11294 if (PHINode *PN = dyn_cast<PHINode>(U))
11295 SE->ConstantEvolutionLoopExitValue.erase(PN);
11296 SE->eraseValueFromMap(U);
11297 Worklist.insert(Worklist.end(), U->user_begin(), U->user_end());
11298 }
11299 // Delete the Old value.
11300 if (PHINode *PN = dyn_cast<PHINode>(Old))
11301 SE->ConstantEvolutionLoopExitValue.erase(PN);
11302 SE->eraseValueFromMap(Old);
11303 // this now dangles!
11304}
11305
11306ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
11307 : CallbackVH(V), SE(se) {}
11308
11309//===----------------------------------------------------------------------===//
11310// ScalarEvolution Class Implementation
11311//===----------------------------------------------------------------------===//
11312
11313ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI,
11314 AssumptionCache &AC, DominatorTree &DT,
11315 LoopInfo &LI)
11316 : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI),
11317 CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64),
11318 LoopDispositions(64), BlockDispositions(64) {
11319 // To use guards for proving predicates, we need to scan every instruction in
11320 // relevant basic blocks, and not just terminators. Doing this is a waste of
11321 // time if the IR does not actually contain any calls to
11322 // @llvm.experimental.guard, so do a quick check and remember this beforehand.
11323 //
11324 // This pessimizes the case where a pass that preserves ScalarEvolution wants
11325 // to _add_ guards to the module when there weren't any before, and wants
11326 // ScalarEvolution to optimize based on those guards. For now we prefer to be
11327 // efficient in lieu of being smart in that rather obscure case.
11328
11329 auto *GuardDecl = F.getParent()->getFunction(
11330 Intrinsic::getName(Intrinsic::experimental_guard));
11331 HasGuards = GuardDecl && !GuardDecl->use_empty();
11332}
11333
11334ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg)
11335 : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT),
11336 LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)),
11337 ValueExprMap(std::move(Arg.ValueExprMap)),
11338 PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)),
11339 PendingPhiRanges(std::move(Arg.PendingPhiRanges)),
11340 PendingMerges(std::move(Arg.PendingMerges)),
11341 MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)),
11342 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)),
11343 PredicatedBackedgeTakenCounts(
11344 std::move(Arg.PredicatedBackedgeTakenCounts)),
11345 ConstantEvolutionLoopExitValue(
11346 std::move(Arg.ConstantEvolutionLoopExitValue)),
11347 ValuesAtScopes(std::move(Arg.ValuesAtScopes)),
11348 LoopDispositions(std::move(Arg.LoopDispositions)),
11349 LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)),
11350 BlockDispositions(std::move(Arg.BlockDispositions)),
11351 UnsignedRanges(std::move(Arg.UnsignedRanges)),
11352 SignedRanges(std::move(Arg.SignedRanges)),
11353 UniqueSCEVs(std::move(Arg.UniqueSCEVs)),
11354 UniquePreds(std::move(Arg.UniquePreds)),
11355 SCEVAllocator(std::move(Arg.SCEVAllocator)),
11356 LoopUsers(std::move(Arg.LoopUsers)),
11357 PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)),
11358 FirstUnknown(Arg.FirstUnknown) {
11359 Arg.FirstUnknown = nullptr;
11360}
11361
11362ScalarEvolution::~ScalarEvolution() {
11363 // Iterate through all the SCEVUnknown instances and call their
11364 // destructors, so that they release their references to their values.
11365 for (SCEVUnknown *U = FirstUnknown; U;) {
11366 SCEVUnknown *Tmp = U;
11367 U = U->Next;
11368 Tmp->~SCEVUnknown();
11369 }
11370 FirstUnknown = nullptr;
11371
11372 ExprValueMap.clear();
11373 ValueExprMap.clear();
11374 HasRecMap.clear();
11375
11376 // Free any extra memory created for ExitNotTakenInfo in the unlikely event
11377 // that a loop had multiple computable exits.
11378 for (auto &BTCI : BackedgeTakenCounts)
11379 BTCI.second.clear();
11380 for (auto &BTCI : PredicatedBackedgeTakenCounts)
11381 BTCI.second.clear();
11382
11383 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage");
11384 assert(PendingPhiRanges.empty() && "getRangeRef garbage");
11385 assert(PendingMerges.empty() && "isImpliedViaMerge garbage");
11386 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!");
11387 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!");
11388}
11389
11390bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
11391 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
11392}
11393
11394static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
11395 const Loop *L) {
11396 // Print all inner loops first
11397 for (Loop *I : *L)
11398 PrintLoopInfo(OS, SE, I);
11399
11400 OS << "Loop ";
11401 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
11402 OS << ": ";
11403
11404 SmallVector<BasicBlock *, 8> ExitBlocks;
11405 L->getExitBlocks(ExitBlocks);
11406 if (ExitBlocks.size() != 1)
11407 OS << "<multiple exits> ";
11408
11409 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
11410 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
11411 } else {
11412 OS << "Unpredictable backedge-taken count. ";
11413 }
11414
11415 OS << "\n"
11416 "Loop ";
11417 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
11418 OS << ": ";
11419
11420 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
11421 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
11422 if (SE->isBackedgeTakenCountMaxOrZero(L))
11423 OS << ", actual taken count either this or zero.";
11424 } else {
11425 OS << "Unpredictable max backedge-taken count. ";
11426 }
11427
11428 OS << "\n"
11429 "Loop ";
11430 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
11431 OS << ": ";
11432
11433 SCEVUnionPredicate Pred;
11434 auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred);
11435 if (!isa<SCEVCouldNotCompute>(PBT)) {
11436 OS << "Predicated backedge-taken count is " << *PBT << "\n";
11437 OS << " Predicates:\n";
11438 Pred.print(OS, 4);
11439 } else {
11440 OS << "Unpredictable predicated backedge-taken count. ";
11441 }
11442 OS << "\n";
11443
11444 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
11445 OS << "Loop ";
11446 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
11447 OS << ": ";
11448 OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n";
11449 }
11450}
11451
11452static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) {
11453 switch (LD) {
11454 case ScalarEvolution::LoopVariant:
11455 return "Variant";
11456 case ScalarEvolution::LoopInvariant:
11457 return "Invariant";
11458 case ScalarEvolution::LoopComputable:
11459 return "Computable";
11460 }
11461 llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!");
11462}
11463
11464void ScalarEvolution::print(raw_ostream &OS) const {
11465 // ScalarEvolution's implementation of the print method is to print
11466 // out SCEV values of all instructions that are interesting. Doing
11467 // this potentially causes it to create new SCEV objects though,
11468 // which technically conflicts with the const qualifier. This isn't
11469 // observable from outside the class though, so casting away the
11470 // const isn't dangerous.
11471 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
11472
11473 OS << "Classifying expressions for: ";
11474 F.printAsOperand(OS, /*PrintType=*/false);
11475 OS << "\n";
11476 for (Instruction &I : instructions(F))
11477 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) {
11478 OS << I << '\n';
11479 OS << " --> ";
11480 const SCEV *SV = SE.getSCEV(&I);
11481 SV->print(OS);
11482 if (!isa<SCEVCouldNotCompute>(SV)) {
11483 OS << " U: ";
11484 SE.getUnsignedRange(SV).print(OS);
11485 OS << " S: ";
11486 SE.getSignedRange(SV).print(OS);
11487 }
11488
11489 const Loop *L = LI.getLoopFor(I.getParent());
11490
11491 const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
11492 if (AtUse != SV) {
11493 OS << " --> ";
11494 AtUse->print(OS);
11495 if (!isa<SCEVCouldNotCompute>(AtUse)) {
11496 OS << " U: ";
11497 SE.getUnsignedRange(AtUse).print(OS);
11498 OS << " S: ";
11499 SE.getSignedRange(AtUse).print(OS);
11500 }
11501 }
11502
11503 if (L) {
11504 OS << "\t\t" "Exits: ";
11505 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
11506 if (!SE.isLoopInvariant(ExitValue, L)) {
11507 OS << "<<Unknown>>";
11508 } else {
11509 OS << *ExitValue;
11510 }
11511
11512 bool First = true;
11513 for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) {
11514 if (First) {
11515 OS << "\t\t" "LoopDispositions: { ";
11516 First = false;
11517 } else {
11518 OS << ", ";
11519 }
11520
11521 Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false);
11522 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter));
11523 }
11524
11525 for (auto *InnerL : depth_first(L)) {
11526 if (InnerL == L)
11527 continue;
11528 if (First) {
11529 OS << "\t\t" "LoopDispositions: { ";
11530 First = false;
11531 } else {
11532 OS << ", ";
11533 }
11534
11535 InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false);
11536 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL));
11537 }
11538
11539 OS << " }";
11540 }
11541
11542 OS << "\n";
11543 }
11544
11545 OS << "Determining loop execution counts for: ";
11546 F.printAsOperand(OS, /*PrintType=*/false);
11547 OS << "\n";
11548 for (Loop *I : LI)
11549 PrintLoopInfo(OS, &SE, I);
11550}
11551
11552ScalarEvolution::LoopDisposition
11553ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) {
11554 auto &Values = LoopDispositions[S];
11555 for (auto &V : Values) {
11556 if (V.getPointer() == L)
11557 return V.getInt();
11558 }
11559 Values.emplace_back(L, LoopVariant);
11560 LoopDisposition D = computeLoopDisposition(S, L);
11561 auto &Values2 = LoopDispositions[S];
11562 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
11563 if (V.getPointer() == L) {
11564 V.setInt(D);
11565 break;
11566 }
11567 }
11568 return D;
11569}
11570
11571ScalarEvolution::LoopDisposition
11572ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
11573 switch (static_cast<SCEVTypes>(S->getSCEVType())) {
11574 case scConstant:
11575 return LoopInvariant;
11576 case scTruncate:
11577 case scZeroExtend:
11578 case scSignExtend:
11579 return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L);
11580 case scAddRecExpr: {
11581 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
11582
11583 // If L is the addrec's loop, it's computable.
11584 if (AR->getLoop() == L)
11585 return LoopComputable;
11586
11587 // Add recurrences are never invariant in the function-body (null loop).
11588 if (!L)
11589 return LoopVariant;
11590
11591 // Everything that is not defined at loop entry is variant.
11592 if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader()))
11593 return LoopVariant;
11594 assert(!L->contains(AR->getLoop()) && "Containing loop's header does not"
11595 " dominate the contained loop's header?");
11596
11597 // This recurrence is invariant w.r.t. L if AR's loop contains L.
11598 if (AR->getLoop()->contains(L))
11599 return LoopInvariant;
11600
11601 // This recurrence is variant w.r.t. L if any of its operands
11602 // are variant.
11603 for (auto *Op : AR->operands())
11604 if (!isLoopInvariant(Op, L))
11605 return LoopVariant;
11606
11607 // Otherwise it's loop-invariant.
11608 return LoopInvariant;
11609 }
11610 case scAddExpr:
11611 case scMulExpr:
11612 case scUMaxExpr:
11613 case scSMaxExpr:
11614 case scUMinExpr:
11615 case scSMinExpr: {
11616 bool HasVarying = false;
11617 for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) {
11618 LoopDisposition D = getLoopDisposition(Op, L);
11619 if (D == LoopVariant)
11620 return LoopVariant;
11621 if (D == LoopComputable)
11622 HasVarying = true;
11623 }
11624 return HasVarying ? LoopComputable : LoopInvariant;
11625 }
11626 case scUDivExpr: {
11627 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
11628 LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L);
11629 if (LD == LoopVariant)
11630 return LoopVariant;
11631 LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L);
11632 if (RD == LoopVariant)
11633 return LoopVariant;
11634 return (LD == LoopInvariant && RD == LoopInvariant) ?
11635 LoopInvariant : LoopComputable;
11636 }
11637 case scUnknown:
11638 // All non-instruction values are loop invariant. All instructions are loop
11639 // invariant if they are not contained in the specified loop.
11640 // Instructions are never considered invariant in the function body
11641 // (null loop) because they are defined within the "loop".
11642 if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue()))
11643 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
11644 return LoopInvariant;
11645 case scCouldNotCompute:
11646 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
11647 }
11648 llvm_unreachable("Unknown SCEV kind!");
11649}
11650
11651bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) {
11652 return getLoopDisposition(S, L) == LoopInvariant;
11653}
11654
11655bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) {
11656 return getLoopDisposition(S, L) == LoopComputable;
11657}
11658
11659ScalarEvolution::BlockDisposition
11660ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) {
11661 auto &Values = BlockDispositions[S];
11662 for (auto &V : Values) {
11663 if (V.getPointer() == BB)
11664 return V.getInt();
11665 }
11666 Values.emplace_back(BB, DoesNotDominateBlock);
11667 BlockDisposition D = computeBlockDisposition(S, BB);
11668 auto &Values2 = BlockDispositions[S];
11669 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
11670 if (V.getPointer() == BB) {
11671 V.setInt(D);
11672 break;
11673 }
11674 }
11675 return D;
11676}
11677
11678ScalarEvolution::BlockDisposition
11679ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
11680 switch (static_cast<SCEVTypes>(S->getSCEVType())) {
11681 case scConstant:
11682 return ProperlyDominatesBlock;
11683 case scTruncate:
11684 case scZeroExtend:
11685 case scSignExtend:
11686 return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB);
11687 case scAddRecExpr: {
11688 // This uses a "dominates" query instead of "properly dominates" query
11689 // to test for proper dominance too, because the instruction which
11690 // produces the addrec's value is a PHI, and a PHI effectively properly
11691 // dominates its entire containing block.
11692 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
11693 if (!DT.dominates(AR->getLoop()->getHeader(), BB))
11694 return DoesNotDominateBlock;
11695
11696 // Fall through into SCEVNAryExpr handling.
11697 LLVM_FALLTHROUGH;
11698 }
11699 case scAddExpr:
11700 case scMulExpr:
11701 case scUMaxExpr:
11702 case scSMaxExpr:
11703 case scUMinExpr:
11704 case scSMinExpr: {
11705 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
11706 bool Proper = true;
11707 for (const SCEV *NAryOp : NAry->operands()) {
11708 BlockDisposition D = getBlockDisposition(NAryOp, BB);
11709 if (D == DoesNotDominateBlock)
11710 return DoesNotDominateBlock;
11711 if (D == DominatesBlock)
11712 Proper = false;
11713 }
11714 return Proper ? ProperlyDominatesBlock : DominatesBlock;
11715 }
11716 case scUDivExpr: {
11717 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
11718 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS();
11719 BlockDisposition LD = getBlockDisposition(LHS, BB);
11720 if (LD == DoesNotDominateBlock)
11721 return DoesNotDominateBlock;
11722 BlockDisposition RD = getBlockDisposition(RHS, BB);
11723 if (RD == DoesNotDominateBlock)
11724 return DoesNotDominateBlock;
11725 return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ?
11726 ProperlyDominatesBlock : DominatesBlock;
11727 }
11728 case scUnknown:
11729 if (Instruction *I =
11730 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) {
11731 if (I->getParent() == BB)
11732 return DominatesBlock;
11733 if (DT.properlyDominates(I->getParent(), BB))
11734 return ProperlyDominatesBlock;
11735 return DoesNotDominateBlock;
11736 }
11737 return ProperlyDominatesBlock;
11738 case scCouldNotCompute:
11739 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
11740 }
11741 llvm_unreachable("Unknown SCEV kind!");
11742}
11743
11744bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
11745 return getBlockDisposition(S, BB) >= DominatesBlock;
11746}
11747
11748bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) {
11749 return getBlockDisposition(S, BB) == ProperlyDominatesBlock;
11750}
11751
11752bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const {
11753 return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; });
11754}
11755
11756bool ScalarEvolution::ExitLimit::hasOperand(const SCEV *S) const {
11757 auto IsS = [&](const SCEV *X) { return S == X; };
11758 auto ContainsS = [&](const SCEV *X) {
11759 return !isa<SCEVCouldNotCompute>(X) && SCEVExprContains(X, IsS);
11760 };
11761 return ContainsS(ExactNotTaken) || ContainsS(MaxNotTaken);
11762}
11763
11764void
11765ScalarEvolution::forgetMemoizedResults(const SCEV *S) {
11766 ValuesAtScopes.erase(S);
11767 LoopDispositions.erase(S);
11768 BlockDispositions.erase(S);
11769 UnsignedRanges.erase(S);
11770 SignedRanges.erase(S);
11771 ExprValueMap.erase(S);
11772 HasRecMap.erase(S);
11773 MinTrailingZerosCache.erase(S);
11774
11775 for (auto I = PredicatedSCEVRewrites.begin();
11776 I != PredicatedSCEVRewrites.end();) {
11777 std::pair<const SCEV *, const Loop *> Entry = I->first;
11778 if (Entry.first == S)
11779 PredicatedSCEVRewrites.erase(I++);
11780 else
11781 ++I;
11782 }
11783
11784 auto RemoveSCEVFromBackedgeMap =
11785 [S, this](DenseMap<const Loop *, BackedgeTakenInfo> &Map) {
11786 for (auto I = Map.begin(), E = Map.end(); I != E;) {
11787 BackedgeTakenInfo &BEInfo = I->second;
11788 if (BEInfo.hasOperand(S, this)) {
11789 BEInfo.clear();
11790 Map.erase(I++);
11791 } else
11792 ++I;
11793 }
11794 };
11795
11796 RemoveSCEVFromBackedgeMap(BackedgeTakenCounts);
11797 RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts);
11798}
11799
11800void
11801ScalarEvolution::getUsedLoops(const SCEV *S,
11802 SmallPtrSetImpl<const Loop *> &LoopsUsed) {
11803 struct FindUsedLoops {
11804 FindUsedLoops(SmallPtrSetImpl<const Loop *> &LoopsUsed)
11805 : LoopsUsed(LoopsUsed) {}
11806 SmallPtrSetImpl<const Loop *> &LoopsUsed;
11807 bool follow(const SCEV *S) {
11808 if (auto *AR = dyn_cast<SCEVAddRecExpr>(S))
11809 LoopsUsed.insert(AR->getLoop());
11810 return true;
11811 }
11812
11813 bool isDone() const { return false; }
11814 };
11815
11816 FindUsedLoops F(LoopsUsed);
11817 SCEVTraversal<FindUsedLoops>(F).visitAll(S);
11818}
11819
11820void ScalarEvolution::addToLoopUseLists(const SCEV *S) {
11821 SmallPtrSet<const Loop *, 8> LoopsUsed;
11822 getUsedLoops(S, LoopsUsed);
11823 for (auto *L : LoopsUsed)
11824 LoopUsers[L].push_back(S);
11825}
11826
11827void ScalarEvolution::verify() const {
11828 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
11829 ScalarEvolution SE2(F, TLI, AC, DT, LI);
11830
11831 SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end());
11832
11833 // Map's SCEV expressions from one ScalarEvolution "universe" to another.
11834 struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> {
11835 SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {}
11836
11837 const SCEV *visitConstant(const SCEVConstant *Constant) {
11838 return SE.getConstant(Constant->getAPInt());
11839 }
11840
11841 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
11842 return SE.getUnknown(Expr->getValue());
11843 }
11844
11845 const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) {
11846 return SE.getCouldNotCompute();
11847 }
11848 };
11849
11850 SCEVMapper SCM(SE2);
11851
11852 while (!LoopStack.empty()) {
11853 auto *L = LoopStack.pop_back_val();
11854 LoopStack.insert(LoopStack.end(), L->begin(), L->end());
11855
11856 auto *CurBECount = SCM.visit(
11857 const_cast<ScalarEvolution *>(this)->getBackedgeTakenCount(L));
11858 auto *NewBECount = SE2.getBackedgeTakenCount(L);
11859
11860 if (CurBECount == SE2.getCouldNotCompute() ||
11861 NewBECount == SE2.getCouldNotCompute()) {
11862 // NB! This situation is legal, but is very suspicious -- whatever pass
11863 // change the loop to make a trip count go from could not compute to
11864 // computable or vice-versa *should have* invalidated SCEV. However, we
11865 // choose not to assert here (for now) since we don't want false
11866 // positives.
11867 continue;
11868 }
11869
11870 if (containsUndefs(CurBECount) || containsUndefs(NewBECount)) {
11871 // SCEV treats "undef" as an unknown but consistent value (i.e. it does
11872 // not propagate undef aggressively). This means we can (and do) fail
11873 // verification in cases where a transform makes the trip count of a loop
11874 // go from "undef" to "undef+1" (say). The transform is fine, since in
11875 // both cases the loop iterates "undef" times, but SCEV thinks we
11876 // increased the trip count of the loop by 1 incorrectly.
11877 continue;
11878 }
11879
11880 if (SE.getTypeSizeInBits(CurBECount->getType()) >
11881 SE.getTypeSizeInBits(NewBECount->getType()))
11882 NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType());
11883 else if (SE.getTypeSizeInBits(CurBECount->getType()) <
11884 SE.getTypeSizeInBits(NewBECount->getType()))
11885 CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType());
11886
11887 auto *ConstantDelta =
11888 dyn_cast<SCEVConstant>(SE2.getMinusSCEV(CurBECount, NewBECount));
11889
11890 if (ConstantDelta && ConstantDelta->getAPInt() != 0) {
11891 dbgs() << "Trip Count Changed!\n";
11892 dbgs() << "Old: " << *CurBECount << "\n";
11893 dbgs() << "New: " << *NewBECount << "\n";
11894 dbgs() << "Delta: " << *ConstantDelta << "\n";
11895 std::abort();
11896 }
11897 }
11898}
11899
11900bool ScalarEvolution::invalidate(
11901 Function &F, const PreservedAnalyses &PA,
11902 FunctionAnalysisManager::Invalidator &Inv) {
11903 // Invalidate the ScalarEvolution object whenever it isn't preserved or one
11904 // of its dependencies is invalidated.
11905 auto PAC = PA.getChecker<ScalarEvolutionAnalysis>();
11906 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) ||
11907 Inv.invalidate<AssumptionAnalysis>(F, PA) ||
11908 Inv.invalidate<DominatorTreeAnalysis>(F, PA) ||
11909 Inv.invalidate<LoopAnalysis>(F, PA);
11910}
11911
11912AnalysisKey ScalarEvolutionAnalysis::Key;
11913
11914ScalarEvolution ScalarEvolutionAnalysis::run(Function &F,
11915 FunctionAnalysisManager &AM) {
11916 return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F),
11917 AM.getResult<AssumptionAnalysis>(F),
11918 AM.getResult<DominatorTreeAnalysis>(F),
11919 AM.getResult<LoopAnalysis>(F));
11920}
11921
11922PreservedAnalyses
11923ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) {
11924 AM.getResult<ScalarEvolutionAnalysis>(F).print(OS);
11925 return PreservedAnalyses::all();
11926}
11927
11928INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution",
11929 "Scalar Evolution Analysis", false, true)
11930INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
11931INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
11932INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
11933INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
11934INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution",
11935 "Scalar Evolution Analysis", false, true)
11936
11937char ScalarEvolutionWrapperPass::ID = 0;
11938
11939ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) {
11940 initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry());
11941}
11942
11943bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) {
11944 SE.reset(new ScalarEvolution(
11945 F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
11946 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
11947 getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
11948 getAnalysis<LoopInfoWrapperPass>().getLoopInfo()));
11949 return false;
11950}
11951
11952void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); }
11953
11954void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const {
11955 SE->print(OS);
11956}
11957
11958void ScalarEvolutionWrapperPass::verifyAnalysis() const {
11959 if (!VerifySCEV)
11960 return;
11961
11962 SE->verify();
11963}
11964
11965void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
11966 AU.setPreservesAll();
11967 AU.addRequiredTransitive<AssumptionCacheTracker>();
11968 AU.addRequiredTransitive<LoopInfoWrapperPass>();
11969 AU.addRequiredTransitive<DominatorTreeWrapperPass>();
11970 AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>();
11971}
11972
11973const SCEVPredicate *ScalarEvolution::getEqualPredicate(const SCEV *LHS,
11974 const SCEV *RHS) {
11975 FoldingSetNodeID ID;
11976 assert(LHS->getType() == RHS->getType() &&
11977 "Type mismatch between LHS and RHS");
11978 // Unique this node based on the arguments
11979 ID.AddInteger(SCEVPredicate::P_Equal);
11980 ID.AddPointer(LHS);
11981 ID.AddPointer(RHS);
11982 void *IP = nullptr;
11983 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
11984 return S;
11985 SCEVEqualPredicate *Eq = new (SCEVAllocator)
11986 SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS);
11987 UniquePreds.InsertNode(Eq, IP);
11988 return Eq;
11989}
11990
11991const SCEVPredicate *ScalarEvolution::getWrapPredicate(
11992 const SCEVAddRecExpr *AR,
11993 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
11994 FoldingSetNodeID ID;
11995 // Unique this node based on the arguments
11996 ID.AddInteger(SCEVPredicate::P_Wrap);
11997 ID.AddPointer(AR);
11998 ID.AddInteger(AddedFlags);
11999 void *IP = nullptr;
12000 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
12001 return S;
12002 auto *OF = new (SCEVAllocator)
12003 SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags);
12004 UniquePreds.InsertNode(OF, IP);
12005 return OF;
12006}
12007
12008namespace {
12009
12010class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> {
12011public:
12012
12013 /// Rewrites \p S in the context of a loop L and the SCEV predication
12014 /// infrastructure.
12015 ///
12016 /// If \p Pred is non-null, the SCEV expression is rewritten to respect the
12017 /// equivalences present in \p Pred.
12018 ///
12019 /// If \p NewPreds is non-null, rewrite is free to add further predicates to
12020 /// \p NewPreds such that the result will be an AddRecExpr.
12021 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
12022 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
12023 SCEVUnionPredicate *Pred) {
12024 SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred);
12025 return Rewriter.visit(S);
12026 }
12027
12028 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
12029 if (Pred) {
12030 auto ExprPreds = Pred->getPredicatesForExpr(Expr);
12031 for (auto *Pred : ExprPreds)
12032 if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred))
12033 if (IPred->getLHS() == Expr)
12034 return IPred->getRHS();
12035 }
12036 return convertToAddRecWithPreds(Expr);
12037 }
12038
12039 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
12040 const SCEV *Operand = visit(Expr->getOperand());
12041 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
12042 if (AR && AR->getLoop() == L && AR->isAffine()) {
12043 // This couldn't be folded because the operand didn't have the nuw
12044 // flag. Add the nusw flag as an assumption that we could make.
12045 const SCEV *Step = AR->getStepRecurrence(SE);
12046 Type *Ty = Expr->getType();
12047 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW))
12048 return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty),
12049 SE.getSignExtendExpr(Step, Ty), L,
12050 AR->getNoWrapFlags());
12051 }
12052 return SE.getZeroExtendExpr(Operand, Expr->getType());
12053 }
12054
12055 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
12056 const SCEV *Operand = visit(Expr->getOperand());
12057 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
12058 if (AR && AR->getLoop() == L && AR->isAffine()) {
12059 // This couldn't be folded because the operand didn't have the nsw
12060 // flag. Add the nssw flag as an assumption that we could make.
12061 const SCEV *Step = AR->getStepRecurrence(SE);
12062 Type *Ty = Expr->getType();
12063 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW))
12064 return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty),
12065 SE.getSignExtendExpr(Step, Ty), L,
12066 AR->getNoWrapFlags());
12067 }
12068 return SE.getSignExtendExpr(Operand, Expr->getType());
12069 }
12070
12071private:
12072 explicit SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE,
12073 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
12074 SCEVUnionPredicate *Pred)
12075 : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {}
12076
12077 bool addOverflowAssumption(const SCEVPredicate *P) {
12078 if (!NewPreds) {
12079 // Check if we've already made this assumption.
12080 return Pred && Pred->implies(P);
12081 }
12082 NewPreds->insert(P);
12083 return true;
12084 }
12085
12086 bool addOverflowAssumption(const SCEVAddRecExpr *AR,
12087 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
12088 auto *A = SE.getWrapPredicate(AR, AddedFlags);
12089 return addOverflowAssumption(A);
12090 }
12091
12092 // If \p Expr represents a PHINode, we try to see if it can be represented
12093 // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible
12094 // to add this predicate as a runtime overflow check, we return the AddRec.
12095 // If \p Expr does not meet these conditions (is not a PHI node, or we
12096 // couldn't create an AddRec for it, or couldn't add the predicate), we just
12097 // return \p Expr.
12098 const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) {
12099 if (!isa<PHINode>(Expr->getValue()))
12100 return Expr;
12101 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
12102 PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr);
12103 if (!PredicatedRewrite)
12104 return Expr;
12105 for (auto *P : PredicatedRewrite->second){
12106 // Wrap predicates from outer loops are not supported.
12107 if (auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) {
12108 auto *AR = cast<const SCEVAddRecExpr>(WP->getExpr());
12109 if (L != AR->getLoop())
12110 return Expr;
12111 }
12112 if (!addOverflowAssumption(P))
12113 return Expr;
12114 }
12115 return PredicatedRewrite->first;
12116 }
12117
12118 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds;
12119 SCEVUnionPredicate *Pred;
12120 const Loop *L;
12121};
12122
12123} // end anonymous namespace
12124
12125const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L,
12126 SCEVUnionPredicate &Preds) {
12127 return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds);
12128}
12129
12130const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates(
12131 const SCEV *S, const Loop *L,
12132 SmallPtrSetImpl<const SCEVPredicate *> &Preds) {
12133 SmallPtrSet<const SCEVPredicate *, 4> TransformPreds;
12134 S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr);
12135 auto *AddRec = dyn_cast<SCEVAddRecExpr>(S);
12136
12137 if (!AddRec)
12138 return nullptr;
12139
12140 // Since the transformation was successful, we can now transfer the SCEV
12141 // predicates.
12142 for (auto *P : TransformPreds)
12143 Preds.insert(P);
12144
12145 return AddRec;
12146}
12147
12148/// SCEV predicates
12149SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID,
12150 SCEVPredicateKind Kind)
12151 : FastID(ID), Kind(Kind) {}
12152
12153SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID,
12154 const SCEV *LHS, const SCEV *RHS)
12155 : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) {
12156 assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match");
12157 assert(LHS != RHS && "LHS and RHS are the same SCEV");
12158}
12159
12160bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const {
12161 const auto *Op = dyn_cast<SCEVEqualPredicate>(N);
12162
12163 if (!Op)
12164 return false;
12165
12166 return Op->LHS == LHS && Op->RHS == RHS;
12167}
12168
12169bool SCEVEqualPredicate::isAlwaysTrue() const { return false; }
12170
12171const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; }
12172
12173void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const {
12174 OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n";
12175}
12176
12177SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID,
12178 const SCEVAddRecExpr *AR,
12179 IncrementWrapFlags Flags)
12180 : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {}
12181
12182const SCEV *SCEVWrapPredicate::getExpr() const { return AR; }
12183
12184bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const {
12185 const auto *Op = dyn_cast<SCEVWrapPredicate>(N);
12186
12187 return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags;
12188}
12189
12190bool SCEVWrapPredicate::isAlwaysTrue() const {
12191 SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags();
12192 IncrementWrapFlags IFlags = Flags;
12193
12194 if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags)
12195 IFlags = clearFlags(IFlags, IncrementNSSW);
12196
12197 return IFlags == IncrementAnyWrap;
12198}
12199
12200void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const {
12201 OS.indent(Depth) << *getExpr() << " Added Flags: ";
12202 if (SCEVWrapPredicate::IncrementNUSW & getFlags())
12203 OS << "<nusw>";
12204 if (SCEVWrapPredicate::IncrementNSSW & getFlags())
12205 OS << "<nssw>";
12206 OS << "\n";
12207}
12208
12209SCEVWrapPredicate::IncrementWrapFlags
12210SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR,
12211 ScalarEvolution &SE) {
12212 IncrementWrapFlags ImpliedFlags = IncrementAnyWrap;
12213 SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags();
12214
12215 // We can safely transfer the NSW flag as NSSW.
12216 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags)
12217 ImpliedFlags = IncrementNSSW;
12218
12219 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) {
12220 // If the increment is positive, the SCEV NUW flag will also imply the
12221 // WrapPredicate NUSW flag.
12222 if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE)))
12223 if (Step->getValue()->getValue().isNonNegative())
12224 ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW);
12225 }
12226
12227 return ImpliedFlags;
12228}
12229
12230/// Union predicates don't get cached so create a dummy set ID for it.
12231SCEVUnionPredicate::SCEVUnionPredicate()
12232 : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {}
12233
12234bool SCEVUnionPredicate::isAlwaysTrue() const {
12235 return all_of(Preds,
12236 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); });
12237}
12238
12239ArrayRef<const SCEVPredicate *>
12240SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) {
12241 auto I = SCEVToPreds.find(Expr);
12242 if (I == SCEVToPreds.end())
12243 return ArrayRef<const SCEVPredicate *>();
12244 return I->second;
12245}
12246
12247bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const {
12248 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N))
12249 return all_of(Set->Preds,
12250 [this](const SCEVPredicate *I) { return this->implies(I); });
12251
12252 auto ScevPredsIt = SCEVToPreds.find(N->getExpr());
12253 if (ScevPredsIt == SCEVToPreds.end())
12254 return false;
12255 auto &SCEVPreds = ScevPredsIt->second;
12256
12257 return any_of(SCEVPreds,
12258 [N](const SCEVPredicate *I) { return I->implies(N); });
12259}
12260
12261const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; }
12262
12263void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const {
12264 for (auto Pred : Preds)
12265 Pred->print(OS, Depth);
12266}
12267
12268void SCEVUnionPredicate::add(const SCEVPredicate *N) {
12269 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) {
12270 for (auto Pred : Set->Preds)
12271 add(Pred);
12272 return;
12273 }
12274
12275 if (implies(N))
12276 return;
12277
12278 const SCEV *Key = N->getExpr();
12279 assert(Key && "Only SCEVUnionPredicate doesn't have an "
12280 " associated expression!");
12281
12282 SCEVToPreds[Key].push_back(N);
12283 Preds.push_back(N);
12284}
12285
12286PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE,
12287 Loop &L)
12288 : SE(SE), L(L) {}
12289
12290const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) {
12291 const SCEV *Expr = SE.getSCEV(V);
12292 RewriteEntry &Entry = RewriteMap[Expr];
12293
12294 // If we already have an entry and the version matches, return it.
12295 if (Entry.second && Generation == Entry.first)
12296 return Entry.second;
12297
12298 // We found an entry but it's stale. Rewrite the stale entry
12299 // according to the current predicate.
12300 if (Entry.second)
12301 Expr = Entry.second;
12302
12303 const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds);
12304 Entry = {Generation, NewSCEV};
12305
12306 return NewSCEV;
12307}
12308
12309const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() {
12310 if (!BackedgeCount) {
12311 SCEVUnionPredicate BackedgePred;
12312 BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred);
12313 addPredicate(BackedgePred);
12314 }
12315 return BackedgeCount;
12316}
12317
12318void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) {
12319 if (Preds.implies(&Pred))
12320 return;
12321 Preds.add(&Pred);
12322 updateGeneration();
12323}
12324
12325const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const {
12326 return Preds;
12327}
12328
12329void PredicatedScalarEvolution::updateGeneration() {
12330 // If the generation number wrapped recompute everything.
12331 if (++Generation == 0) {
12332 for (auto &II : RewriteMap) {
12333 const SCEV *Rewritten = II.second.second;
12334 II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)};
12335 }
12336 }
12337}
12338
12339void PredicatedScalarEvolution::setNoOverflow(
12340 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
12341 const SCEV *Expr = getSCEV(V);
12342 const auto *AR = cast<SCEVAddRecExpr>(Expr);
12343
12344 auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE);
12345
12346 // Clear the statically implied flags.
12347 Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags);
12348 addPredicate(*SE.getWrapPredicate(AR, Flags));
12349
12350 auto II = FlagsMap.insert({V, Flags});
12351 if (!II.second)
12352 II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second);
12353}
12354
12355bool PredicatedScalarEvolution::hasNoOverflow(
12356 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
12357 const SCEV *Expr = getSCEV(V);
12358 const auto *AR = cast<SCEVAddRecExpr>(Expr);
12359
12360 Flags = SCEVWrapPredicate::clearFlags(
12361 Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE));
12362
12363 auto II = FlagsMap.find(V);
12364
12365 if (II != FlagsMap.end())
12366 Flags = SCEVWrapPredicate::clearFlags(Flags, II->second);
12367
12368 return Flags == SCEVWrapPredicate::IncrementAnyWrap;
12369}
12370
12371const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) {
12372 const SCEV *Expr = this->getSCEV(V);
12373 SmallPtrSet<const SCEVPredicate *, 4> NewPreds;
12374 auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds);
12375
12376 if (!New)
12377 return nullptr;
12378
12379 for (auto *P : NewPreds)
12380 Preds.add(P);
12381
12382 updateGeneration();
12383 RewriteMap[SE.getSCEV(V)] = {Generation, New};
12384 return New;
12385}
12386
12387PredicatedScalarEvolution::PredicatedScalarEvolution(
12388 const PredicatedScalarEvolution &Init)
12389 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds),
12390 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) {
12391 for (const auto &I : Init.FlagsMap)
12392 FlagsMap.insert(I);
12393}
12394
12395void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const {
12396 // For each block.
12397 for (auto *BB : L.getBlocks())
12398 for (auto &I : *BB) {
12399 if (!SE.isSCEVable(I.getType()))
12400 continue;
12401
12402 auto *Expr = SE.getSCEV(&I);
12403 auto II = RewriteMap.find(Expr);
12404
12405 if (II == RewriteMap.end())
12406 continue;
12407
12408 // Don't print things that are not interesting.
12409 if (II->second.second == Expr)
12410 continue;
12411
12412 OS.indent(Depth) << "[PSE]" << I << ":\n";
12413 OS.indent(Depth + 2) << *Expr << "\n";
12414 OS.indent(Depth + 2) << "--> " << *II->second.second << "\n";
12415 }
12416}
12417
12418// Match the mathematical pattern A - (A / B) * B, where A and B can be
12419// arbitrary expressions.
12420// It's not always easy, as A and B can be folded (imagine A is X / 2, and B is
12421// 4, A / B becomes X / 8).
12422bool ScalarEvolution::matchURem(const SCEV *Expr, const SCEV *&LHS,
12423 const SCEV *&RHS) {
12424 const auto *Add = dyn_cast<SCEVAddExpr>(Expr);
12425 if (Add == nullptr || Add->getNumOperands() != 2)
12426 return false;
12427
12428 const SCEV *A = Add->getOperand(1);
12429 const auto *Mul = dyn_cast<SCEVMulExpr>(Add->getOperand(0));
12430
12431 if (Mul == nullptr)
12432 return false;
12433
12434 const auto MatchURemWithDivisor = [&](const SCEV *B) {
12435 // (SomeExpr + (-(SomeExpr / B) * B)).
12436 if (Expr == getURemExpr(A, B)) {
12437 LHS = A;
12438 RHS = B;
12439 return true;
12440 }
12441 return false;
12442 };
12443
12444 // (SomeExpr + (-1 * (SomeExpr / B) * B)).
12445 if (Mul->getNumOperands() == 3 && isa<SCEVConstant>(Mul->getOperand(0)))
12446 return MatchURemWithDivisor(Mul->getOperand(1)) ||
12447 MatchURemWithDivisor(Mul->getOperand(2));
12448
12449 // (SomeExpr + ((-SomeExpr / B) * B)) or (SomeExpr + ((SomeExpr / B) * -B)).
12450 if (Mul->getNumOperands() == 2)
12451 return MatchURemWithDivisor(Mul->getOperand(1)) ||
12452 MatchURemWithDivisor(Mul->getOperand(0)) ||
12453 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(1))) ||
12454 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(0)));
12455 return false;
12456}
12457